CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-lottie-react

React wrapper for Lottie animations providing Component and Hook APIs with interactivity support.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

hook-api.mddocs/

Hook API

Hook-based API providing programmatic control over Lottie animations with method returns for play, pause, stop, and other animation controls.

Capabilities

useLottie Hook

Core hook for managing Lottie animations with programmatic control, returning a View component and animation control methods.

/**
 * Hook for managing Lottie animations with programmatic control
 * @param props - Lottie configuration options
 * @param style - Optional CSS styles for the animation container
 * @returns Object containing View component and control methods
 */
function useLottie<T extends RendererType = "svg">(
  props: LottieOptions<T>,
  style?: CSSProperties
): { View: ReactElement } & LottieRefCurrentProps;

Usage Examples:

import React from "react";
import { useLottie } from "lottie-react";
import animationData from "./animation.json";

// Basic hook usage
const BasicHookAnimation = () => {
  const { View } = useLottie({
    animationData,
    loop: true,
    autoplay: true,
  });

  return <div>{View}</div>;
};

// With programmatic controls
const ControlledAnimation = () => {
  const { View, play, pause, stop, setSpeed } = useLottie({
    animationData,
    loop: true,
    autoplay: false,
  });

  return (
    <div>
      <div style={{ marginBottom: 20 }}>{View}</div>
      <div>
        <button onClick={play}>Play</button>
        <button onClick={pause}>Pause</button>
        <button onClick={stop}>Stop</button>
        <button onClick={() => setSpeed(2)}>2x Speed</button>
        <button onClick={() => setSpeed(0.5)}>0.5x Speed</button>
      </div>
    </div>
  );
};

// With custom styling
const StyledHookAnimation = () => {
  const { View, animationLoaded } = useLottie(
    {
      animationData,
      loop: false,
      autoplay: true,
    },
    { 
      width: 300, 
      height: 300, 
      border: "1px solid #ccc",
      borderRadius: "8px"
    }
  );

  return (
    <div>
      {!animationLoaded && <div>Loading animation...</div>}
      {View}
    </div>
  );
};

// With advanced controls
const AdvancedControls = () => {
  const { 
    View, 
    play, 
    pause, 
    goToAndStop, 
    goToAndPlay, 
    playSegments,
    getDuration,
    setDirection 
  } = useLottie({
    animationData,
    loop: false,
    autoplay: false,
  });

  const handleGoToFrame = (frame: number) => {
    goToAndStop(frame, true);
  };

  const handlePlaySegment = () => {
    playSegments([10, 50], true);
  };

  const handleReverse = () => {
    setDirection(-1);
    play();
  };

  return (
    <div>
      {View}
      <div>
        <button onClick={() => handleGoToFrame(0)}>Go to Start</button>
        <button onClick={() => handleGoToFrame(25)}>Go to Middle</button>
        <button onClick={handlePlaySegment}>Play Segment 10-50</button>
        <button onClick={handleReverse}>Play Reverse</button>
        <p>Duration: {getDuration()} seconds</p>
      </div>
    </div>
  );
};

// With event handling
const EventHandledAnimation = () => {
  const { View } = useLottie({
    animationData,
    loop: true,
    autoplay: true,
    onComplete: () => console.log("Animation completed"),
    onLoopComplete: () => console.log("Loop completed"),
    onEnterFrame: (event) => console.log("Current frame:", event.currentTime),
  });

  return View;
};

Hook Return Value

The useLottie hook returns an object containing the View component and all animation control methods.

interface UseLottieReturn extends LottieRefCurrentProps {
  /** React element containing the Lottie animation */
  View: ReactElement;
}

interface LottieRefCurrentProps {
  /** Start/resume animation playback */
  play: () => void;
  /** Stop animation and reset to beginning */
  stop: () => void;
  /** Pause animation at current frame */
  pause: () => void;
  /** Set animation playback speed (1 = normal, 2 = double speed, 0.5 = half speed) */
  setSpeed: (speed: number) => void;
  /** Go to specific frame or time and stop there */
  goToAndStop: (value: number, isFrame?: boolean) => void;
  /** Go to specific frame or time and start playing from there */
  goToAndPlay: (value: number, isFrame?: boolean) => void;
  /** Set animation direction (1 = forward, -1 = reverse) */
  setDirection: (direction: AnimationDirection) => void;
  /** Play specific segments of the animation */
  playSegments: (segments: AnimationSegment | AnimationSegment[], forceFlag?: boolean) => void;
  /** Enable/disable subframe rendering for smoother animation */
  setSubframe: (useSubFrames: boolean) => void;
  /** Get animation duration in seconds (default) or frames */
  getDuration: (inFrames?: boolean) => number | undefined;
  /** Destroy animation instance and clean up resources */
  destroy: () => void;
  /** Ref to the animation container DOM element */
  animationContainerRef: RefObject<HTMLDivElement>;
  /** Whether animation data has been loaded and is ready */
  animationLoaded: boolean;
  /** Direct access to the underlying lottie-web AnimationItem */
  animationItem: AnimationItem | undefined;
}

Hook Parameters

Configuration options for the useLottie hook.

interface LottieOptions<T extends RendererType = "svg"> extends 
  Omit<AnimationConfigWithData<T>, "container" | "animationData">, 
  Omit<React.HTMLProps<HTMLDivElement>, "loop"> {
  /** Animation data object (required) - JSON exported from After Effects */
  animationData: unknown;
  /** Optional ref for external access to animation controls */
  lottieRef?: LottieRef;
  /** Whether to loop the animation (default: false) */
  loop?: boolean;
  /** Whether to start playing automatically (default: true) */
  autoplay?: boolean;
  /** Animation renderer: "svg" (default), "canvas", or "html" */
  renderer?: T;
  /** Animation name for debugging purposes */
  name?: string;
  /** Base path for loading animation assets */
  assetsPath?: string;
  /** Initial segment to play [startFrame, endFrame] */
  initialSegment?: AnimationSegment;
  /** Renderer-specific configuration options */
  rendererSettings?: any;
  
  // Event handlers - all optional
  /** Called when animation completes (non-looping animations) */
  onComplete?: AnimationEventCallback | null;
  /** Called when each loop completes (looping animations) */
  onLoopComplete?: AnimationEventCallback | null;
  /** Called on each animation frame - use sparingly for performance */
  onEnterFrame?: AnimationEventCallback | null;
  /** Called when animation segment starts playing */
  onSegmentStart?: AnimationEventCallback | null;
  /** Called when animation configuration is ready */
  onConfigReady?: AnimationEventCallback | null;
  /** Called when animation data is loaded and ready */
  onDataReady?: AnimationEventCallback | null;
  /** Called if animation data fails to load */
  onDataFailed?: AnimationEventCallback | null;
  /** Called when all images in animation are loaded */
  onLoadedImages?: AnimationEventCallback | null;
  /** Called when DOM elements are loaded */
  onDOMLoaded?: AnimationEventCallback | null;
  /** Called when animation instance is destroyed */
  onDestroy?: AnimationEventCallback | null;
}

Animation Control Methods

Detailed descriptions of all animation control methods returned by the hook.

/**
 * Start or resume animation playback from current position
 */
play: () => void;

/**
 * Stop animation and reset playhead to beginning
 */
stop: () => void;

/**
 * Pause animation at current position
 */
pause: () => void;

/**
 * Set animation playback speed
 * @param speed - Playback speed multiplier (1 = normal, 2 = double, 0.5 = half)
 */
setSpeed: (speed: number) => void;

/**
 * Jump to specific frame or time and stop there
 * @param value - Frame number or time in seconds
 * @param isFrame - Whether value is frame number (true) or seconds (false)
 */
goToAndStop: (value: number, isFrame?: boolean) => void;

/**
 * Jump to specific frame or time and start playing from there
 * @param value - Frame number or time in seconds  
 * @param isFrame - Whether value is frame number (true) or seconds (false)
 */
goToAndPlay: (value: number, isFrame?: boolean) => void;

/**
 * Set animation playback direction
 * @param direction - 1 for forward, -1 for reverse
 */
setDirection: (direction: AnimationDirection) => void;

/**
 * Play specific segments of the animation
 * @param segments - Single segment [start, end] or array of segments
 * @param forceFlag - Whether to force immediate segment playback
 */
playSegments: (
  segments: AnimationSegment | AnimationSegment[], 
  forceFlag?: boolean
) => void;

/**
 * Enable or disable subframe rendering for smoother animation
 * @param useSubFrames - Whether to use subframe rendering
 */
setSubframe: (useSubFrames: boolean) => void;

/**
 * Get the total duration of the animation
 * @param inFrames - Return duration in frames (true) or seconds (false)
 * @returns Duration value or undefined if not loaded
 */
getDuration: (inFrames?: boolean) => number | undefined;

/**
 * Destroy the animation instance and clean up all resources
 * Should be called when component unmounts or animation is no longer needed
 */
destroy: () => void;

Types

type RendererType = "svg" | "canvas" | "html";
type AnimationDirection = 1 | -1;
type AnimationSegment = [number, number];
type AnimationEventCallback<T = any> = (event: T) => void;
type LottieRef = MutableRefObject<LottieRefCurrentProps | null>;

interface AnimationItem {
  // Core lottie-web AnimationItem interface
  play(): void;
  stop(): void;
  pause(): void;
  destroy(): void;
  setSpeed(speed: number): void;
  goToAndStop(value: number, isFrame?: boolean): void;
  goToAndPlay(value: number, isFrame?: boolean): void;
  setDirection(direction: AnimationDirection): void;
  playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag?: boolean): void;
  getDuration(inFrames?: boolean): number;
  // ... additional lottie-web properties
}

docs

component-api.md

hook-api.md

index.md

interactivity-api.md

tile.json