lottie-react

repository·main·Indexed 21 days ago

https://github.com/gamote/lottie-react

A React wrapper for lottie-web that provides components and hooks to integrate Lottie animations. It includes the <Lottie /> component for rendering animations via JSON data, the useLottie hook for direct instance control, and the useLottieInteractivity hook to synchronize animations with scroll or cursor movements. Supports programmatic control methods such as play, pause, seek, and setSpeed.

Tokens
5.7K
Snippets
15
Records
22
Agent score
76%

What's inside lottie-react

  1. Sync Lottie animation with cursor movement

    main

    To sync animation with the cursor, set mode to "cursor". You can use the position property to map cursor coordinates to animation frames.

    • Diagonal Sync: Map x: [0, 1] and y: [0, 1] to a seek action to complete the animation as the cursor moves from top-left to bottom-right.
    • Horizontal/Vertical Sync: Map only one axis (e.g., x: [0, 1]) to sync movement along that axis.
    • Hover Effects: Use position: { x: [0, 1], y: [0, 1] } with a loop type to play a segment while the cursor is inside, and a position: { x: -1, y: -1 } with a stop type to halt it when the cursor leaves.
    // Example: Play segments on hover
    const PlaySegmentsOnHover = () => {
      const lottieObj = useLottie(options, style);
      const Animation = useLottieInteractivity({
        lottieObj,
        mode: "cursor",
        actions: [
          {
            position: { x: [0, 1], y: [0, 1] },
            type: "loop",
            frames: [45, 60],
          },
          {
            position: { x: -1, y: -1 },
            type: "stop",
            frames: [45],
          },
        ],
      });
    
      return Animation;
    };
  2. Install lottie-react

    main

    Install lottie-react using npm or yarn.

    Prerequisites: Ensure you have react and react-dom installed. Because this library uses React Hooks, the minimum required version for both react and react-dom is v16.8.0.

    yarn add lottie-react
    # or
    npm i lottie-react
  3. Use the useLottieInteractivity hook

    main

    The useLottieInteractivity hook allows you to sync Lottie animations with user interactions like scrolling or cursor movement. It must be used in conjunction with the useLottie hook. The hook returns a React.Element which you should render in your component to apply the interactivity logic.

    To use it, pass the lottieObj (returned from useLottie), a mode ("scroll" or "cursor"), and an array of actions that define how the animation behaves during specific interaction states.

    import { useLottie, useLottieInteractivity } from "lottie-react";
    import likeButton from "./likeButton.json";
    
    const options = { animationData: likeButton };
    
    const Example = () => {
      const lottieObj = useLottie(options);
      const Animation = useLottieInteractivity({
        lottieObj,
        mode: "scroll",
        actions: [
          {
            visibility: [0.4, 0.9],
            type: "seek",
            frames: [0, 38],
          },
        ],
      });
    
      return Animation;
    };
  4. Use the Lottie component

    main

    To render a Lottie animation, import the Lottie component and provide the animationData prop with a JSON object containing your exported animation data.

    import Lottie from "lottie-react";
    import groovyWalkAnimation from "./groovyWalk.json";
    
    const Example = () => {
      return <Lottie animationData={groovyWalkAnimation} />;
    };
    
    export default Example;
  5. Configure interactivity actions for scroll and cursor modes

    main

    Interactivity is driven by an array of actions. Each action defines a trigger condition and a resulting animation behavior.

    Action Types

    • seek: Moves the animation to a specific frame.
      • In scroll mode: Maps the container's visibility percentage to a frame range.
      • In cursor mode: Maps the average of X and Y cursor position percentages to a frame range.
    • loop: Plays a specific segment of the animation repeatedly.
    • play: Resets segments and plays the animation.
    • stop: Stops the animation at a specific frame.

    Trigger Conditions

    • For scroll mode: Uses the visibility property, which is an array [startPercent, endPercent] (e.g., [0.2, 0.8]) representing when the action should trigger based on the container's position in the viewport.
    • For cursor mode: Uses the position property. This can be a specific coordinate { x, y } or a bounding box defined by arrays x: [min, max] and y: [min, max].
  6. Sync Lottie animation with scroll (with offset)

    main

    To create a scroll effect where the animation is stopped for a portion of the scroll and then synced (seeked) for the rest, provide multiple action objects in the actions array. The visibility property determines when each action triggers based on the container's scroll position.

    import { useLottie, useLottieInteractivity } from "lottie-react";
    import likeButton from "./likeButton.json";
    
    const options = {
      animationData: likeButton,
    };
    
    const Example = () => {
      const lottieObj = useLottie(options);
      const Animation = useLottieInteractivity({
        lottieObj,
        mode: "scroll",
        actions: [
          {
            visibility: [0, 0.45],
            type: "stop",
            frames: [0],
          },
          {
            visibility: [0.45, 1],
            type: "seek",
            frames: [0, 38],
          },
        ],
      });
    
      return Animation;
    };
    
    export default Example;
  7. Sync Lottie animation with scroll or cursor

    main

    Use the interactivity prop to synchronize the animation with user interactions like scrolling or mouse movement. For detailed implementation, refer to the useLottieInteractivity hook.

    An interactivity object requires a mode (e.g., 'scroll') and an array of actions. Each action defines a visibility range (as a percentage of the viewport/container) and the type of animation action to perform (e.g., 'stop', 'seek', 'loop').

    import Lottie from "lottie-react";
    import robotAnimation from "./robotAnimation.json";
    
    const style = { height: 300 };
    
    const interactivity = {
      mode: "scroll",
      actions: [
        {
          visibility: [0, 0.2],
          type: "stop",
          frames: [0],
        },
        {
          visibility: [0.2, 0.45],
          type: "seek",
          frames: [0, 45],
        },
        {
          visibility: [0.45, 1.0],
          type: "loop",
          frames: [45, 60],
        },
      ],
    };
    
    const Example = () => {
      return (
        <Lottie
          animationData={robotAnimation}
          style={style}
          interactivity={interactivity}
        />
      );
    };
    import Lottie from "lottie-react";
    import robotAnimation from "./robotAnimation.json";
    
    const style = {
      height: 300,
    };
    
    const interactivity = {
      mode: "scroll",
      actions: [
        {
          visibility: [0, 0.2],
          type: "stop",
          frames: [0],
        },
        {
          visibility: [0.2, 0.45],
          type: "seek",
          frames: [0, 45],
        },
        {
          visibility: [0.45, 1.0],
          type: "loop",
          frames: [45, 60],
        },
      ],
    };
    
    const Example = () => {
      return (
        <Lottie
          animationData={robotAnimation}
          style={style}
          interactivity={interactivity}
        />
      );
    };
  8. Configure useLottieInteractivity parameters

    main

    The useLottieInteractivity hook accepts the following parameters:

    • lottieObj (required): The object returned from the useLottie() hook.
    • mode (required): The event type to sync with. Either "scroll" or "cursor".
    • actions (required): An array of action objects that run in sequence. One action chains to the next.

    Action Object Schema

    Each action object in the actions array defines how the animation behaves:

    • frames (number | [number, number]): The frame range.
      • [0, 150] plays the full range.
      • [50, 120] plays a specific segment.
      • [80] freezes the animation at frame 80.
    • type ("seek" | "play" | "stop" | "loop"):
      • "seek": Plays animation frame-by-frame as you scroll or move the cursor.
      • "play", "stop", "loop": Standard animation controls.
    • visibility ([number, number], optional): (mode: "scroll" only) A viewport percentage (0 to 1) representing the height of the Lottie container. For example, [0.4, 0.85] starts the action when 40% of the container is scrolled and ends at 85%.
    • position ({ x: number | [number, number], y: number | [number, number] }, optional): (mode: "cursor" only) Defines how cursor movement maps to the animation element.
      • { x: [0, 1], y: [0, 1] }: Cursor covers the entire element.
      • { x: -1, y: -1 }: Cursor is outside the element.
  9. Control animations with useLottie return methods

    main

    The useLottie hook returns an object containing the View React element and a set of methods to control the animation instance. These methods allow you to manipulate playback, speed, and segments programmatically.

    // The returned object contains:
    // Lottie.View: React.Element
    // Lottie.play(): method
    // Lottie.stop(): method
    // Lottie.pause(): method
    // Lottie.setSpeed(): method
    // Lottie.goToAndStop(): method
    // Lottie.goToAndPlay(): method
    // Lottie.setDirection(): method
    // Lottie.playSegments(): method
    // Lottie.setSubframe(): method
    // Lottie.getDuration(): method
    // Lottie.destroy(): method
  10. Use the useLottie hook

    main

    The useLottie hook provides a way to render a Lottie animation and gives you direct access to the underlying Lottie instance methods. It returns an object containing a View component (a div wrapper) and several control methods like play, pause, and stop.

    To use it, pass an options object containing the animationData and an optional style object for the wrapper.

    import { useLottie } from "lottie-react";
    import groovyWalkAnimation from "./groovyWalk.json";
    
    const style = {
      height: 300,
    };
    
    const Example = () => {
      const options = {
        animationData: groovyWalkAnimation,
        loop: true,
        autoplay: true,
      };
    
      const { View } = useLottie(options, style);
    
      return View;
    };
    
    export default Example;
  11. Control Lottie animations with interaction methods

    main

    You can programmatically control the animation (play, pause, seek, etc.) by passing a React ref to the lottieRef prop. The methods are accessible via lottieRef.current.

    Setup

    import { useRef } from "react";
    import Lottie from "lottie-react";
    import groovyWalkAnimation from "./groovyWalk.json";
    
    const Example = () => {
      const lottieRef = useRef();
    
      return <Lottie lottieRef={lottieRef} animationData={groovyWalkAnimation} />;
    };

    Available Methods

    MethodParametersDescription
    play()-Starts the animation.
    stop()-Stops the animation.
    pause()-Pauses the animation.
    setSpeed(speed)speed: numberSets playback speed (1 is normal).
    goToAndPlay(value, isFrame)value: number, isFrame: booleanSeeks to a value and plays. isFrame defaults to false (time-based).
    goToAndStop(value, isFrame)value: number, isFrame: booleanSeeks to a value and stops. isFrame defaults to false (time-based).
    setDirection(direction)direction: 1 | -11 for forward, -1 for reverse.
    playSegments(segments, forceFlag)segments: Array, forceFlag: booleanPlays specific segments. forceFlag: true updates immediately; false waits for current segment to finish.
    setSubframe(useSubFrames)useSubFrames: booleanIf true (default), updates on every requestAnimationFrame. If false, respects original AE fps.
    getDuration(inFrames)inFrames: booleanReturns duration. If true, returns frames; if false, returns seconds.
    destroy()-Destroys the animation instance.

    Example usage:

    lottieRef.current.pause();
    import Lottie from "lottie-react";
    import groovyWalkAnimation from "./groovyWalk.json";
    import { useRef } from "react";
    
    const Example = () => {
      const lottieRef = useRef();
    
      return <Lottie lottieRef={lottieRef} animationData={groovyWalkAnimation} />;
    };
  12. Configure Lottie Interactivity

    main

    The interactivity prop allows you to trigger animation actions based on user interaction or scroll position. It is part of LottieComponentProps.

    Modes:

    • cursor: Triggers actions based on mouse/pointer position.
    • scroll: Triggers actions based on the scroll position of the container.

    Actions: An Action defines what happens during an interaction:

    • type: The action to perform ('seek', 'play', 'stop', or 'loop').
    • frames: The specific frames to target: [number] or [number, number] (a segment).
    • visibility: An optional range [number, number] defining when the action is active.
    • position: An optional Position object defining where on the x or y axis the action occurs.
    const interactivity = {
      mode: 'scroll' as const,
      actions: [
        {
          type: 'play' as const,
          frames: [0, 60],
          visibility: [0, 100],
        },
      ],
    };
    
    <Lottie animationData={data} interactivity={interactivity} />