react-native-skottie

repository·main·Indexed 21 days ago

https://github.com/margelo/react-native-skottie

A high-performance library for running Lottie and DotLottie animations in React Native using Skia's GPU-acceleration. It provides higher frame rates and lower CPU usage than traditional Lottie libraries and is designed as a drop-in replacement for lottie-react-native. It supports imperative control via SkottieViewRef, progress-based control using React Native Reanimated shared values, and manual instance creation via SkottieAPI.

Tokens
4.2K
Snippets
16
Records
23
Agent score
76%

What's inside react-native-skottie

  1. Configure Proguard for Android release builds

    main

    If you are using Proguard in your Android release builds, you must add the following rules to your proguard-rules.pro file to prevent Skia and Skottie classes from being stripped:

    # for skia, if you haven't add it
    -keep class com.shopify.reactnative.skia.** { *; }
    
    # for skottie
    -keep class com.skiaskottie.** { *; }
  2. Control animation progress with Reanimated

    main

    To drive an animation using a Reanimated SharedValue, pass the value to the progress prop. This allows for high-performance, frame-perfect control of the animation state (e.g., scrubbing through an animation based on scroll position).

    When progress is provided, autoPlay and speed/duration props are ignored as the animation is driven externally.

    import { useSharedValue } from 'react-native-reanimated';
    import { Skottie } from 'react-native-skottie';
    
    const progress = useSharedValue(0);
    
    // ...
    <Skottie 
      source={require('./animation.json')} 
      progress={progress} 
    />
  3. Handle peerDependencies in Metro configuration

    main

    When working in a monorepo or an example project where react-native-skottie has peer dependencies, you may need to prevent multiple versions of those dependencies from being loaded. This is achieved by:

    1. Adding the peer dependency paths to resolver.blacklistRE (using metro-config/src/defaults/exclusionList) to block them at the root.
    2. Using resolver.extraNodeModules to alias those dependencies to the specific versions located in the local node_modules folder.

    Additionally, ensure any paths containing externals/skia/ are included in the blacklistRE regex to avoid conflicts.

    const modules = Object.keys({ ...pak.peerDependencies });
    
    const config = {
      resolver: {
        blacklistRE: exclusionList([
          ...modules.map(
            (m) => new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
          ),
          new RegExp('.*externals\\/skia\\/.*'),
        ]),
        extraNodeModules: modules.reduce((acc, name) => {
          acc[name] = path.join(__dirname, 'node_modules', name);
          return acc;
        }, {}),
      },
    };
  4. Use the Skottie component

    main

    The Skottie component is the primary React component for rendering Lottie animations via Skia.

    Important Setup Requirement: You must import @shopify/react-native-skia at the top of your file to ensure the Skia module is registered before using Skottie.

    Basic Usage

    import '@shopify/react-native-skia';
    import { Skottie } from 'react-native-skottie';
    
    // ...
    <Skottie 
      source={require('./animation.json')} 
      autoPlay={true} 
      loop={true} 
    />
    import '@shopify/react-native-skia';
    import { Skottie } from 'react-native-skottie';
    
    <Skottie 
      source={require('./animation.json')} 
      autoPlay={true} 
      loop={true} 
    />
  5. Basic usage of the Skottie component

    main

    Use the Skottie component to render Lottie (JSON) or DotLottie (.lottie) animations. It is designed as a drop-in replacement for lottie-react-native.

    import { Skottie } from 'react-native-skottie';
    // DotLottie files are supported as well!
    import LottieAnimationFile from './animation.json';
    
    export default function App() {
      return (
        <Skottie
          style={styles.flex1}
          source={LottieAnimationFile}
          autoPlay={true}
        />
      );
    }
  6. Control Skottie imperatively using a ref

    main

    You can control the animation playback (play, pause, reset) using a SkottieViewRef attached to the Skottie component.

    import { Skottie, SkottieViewRef } from 'react-native-skottie';
    import { Button, View } from 'react-native';
    import { useRef } from 'react';
    import LottieAnimationFile from './animation.json';
    
    export default function App() {
      const skottieRef = useRef<SkottieViewRef>(null);
    
      return (
        <View>
          <Skottie
            ref={skottieRef}
            style={styles.flex1}
            source={LottieAnimationFile}
          />
    
          <Button
            title="Play"
            onPress={() => skottieRef.current?.play()}
          />
          <Button
            title="Pause"
            onPress={() => skottieRef.current?.pause()}
          />
          <Button
            title="Reset"
            onPress={() => skottieRef.current?.reset()}
          />
        </View>
      );
    }
  7. Control Skottie with React Native Reanimated

    main

    To drive an animation using a Reanimated SharedValue (e.g., for scrubbing or custom easing), pass a progress shared value (from 0 to 1) to the Skottie component.

    Note: When using the progress prop, neither the autoPlay prop nor the imperative ref API will work; you are responsible for controlling the animation state via the shared value.

    To determine the animation duration for your Reanimated timing, use SkottieAPI.createFrom(source) to create a SkSkottie instance.

    import { Skottie, SkottieAPI } from 'react-native-skottie';
    import { useSharedValue, withTiming, Easing } from 'react-native-reanimated';
    import { useMemo, useEffect } from 'react';
    
    export default function App() {
      const progress = useSharedValue(0);
      const lottieFile = require('./animation.json');
    
      // Get duration from the Skottie instance
      const skottieAnimation = useMemo(() => SkottieAPI.createFrom(lottieFile), []);
      const duration = skottieAnimation.duration;
    
      useEffect(() => {
        progress.value = withTiming(1, {
          duration: duration * 1000,
          easing: Easing.linear,
        });
      }, [duration]);
    
      return (
        <Skottie
          autoPlay={true}
          style={styles.flex1}
          source={lottieFile}
          progress={progress}
        />
      );
    }
  8. Configure autolinking for react-native-skottie in a monorepo

    main

    When using react-native-skottie within a monorepo structure, you may need to manually configure autolinking in your react-native.config.js file. This ensures that the React Native CLI can correctly locate the package's native source code by pointing the root property to the directory containing the package's package.json.

    const path = require('path');
    const pak = require('../package.json');
    
    module.exports = {
      dependencies: {
        [pak.name]: {
          root: path.join(__dirname, '..'),
        },
      },
    };
  9. SkottieAPI reference

    main

    The SkottieAPI allows you to create SkSkottie instances manually. This is useful for inspecting animation metadata like duration before rendering.

    // Example usage of SkottieAPI
    const skottieAnimation = SkottieAPI.createFrom(source);
    console.log(skottieAnimation.duration);