React Logoreact-lottie

React-lottie is a React component that acts as a wrapper around the Lottie web player library, enabling developers to easily integrate high-quality, lightweight Lottie animations into their React applications. Lottie, developed by Airbnb, is a powerful open-source animation tool that parses Adobe After Effects animations (exported as JSON files using the Bodymovin plugin) and renders them natively on mobile (Android and iOS) and the web. This means designers can create complex animations in After Effects, and developers can render them in their apps without having to recreate them manually using code or dealing with large, inefficient GIF/video files.

Key features and benefits of using `react-lottie` include:

1. Ease of Integration: It simplifies the process of embedding Lottie animations into React components with minimal setup and a familiar prop-based interface.
2. Performance: Lottie animations are vector-based, resulting in extremely small file sizes compared to traditional raster-based formats like GIFs or videos. They also scale perfectly to any resolution without pixelation, maintaining crisp quality.
3. Customization and Control: Developers gain fine-grained control over various aspects of the animation's playback. This includes settings for autoplay, looping, playback speed, animation direction, and even playing specific segments of an animation. It also provides props (`isPaused`, `isStopped`) for dynamically pausing, resuming, and stopping the animation.
4. Event Handling: `react-lottie` exposes various lifecycle events (e.g., `complete`, `loopComplete`, `enterFrame`) that allow developers to attach listeners and trigger specific actions or UI updates at different stages of the animation playback.
5. Cross-platform Consistency: Animations rendered with Lottie look identical across web, iOS, and Android platforms, ensuring a consistent and branded user experience.

To use `react-lottie`, you typically install it via npm or yarn, import the `Lottie` component, and then pass an animation JSON file (which you would have exported from After Effects) along with configuration options (like `loop`, `autoplay`, and `rendererSettings`) to its `options` prop. This makes it an invaluable tool for adding dynamic and engaging visual elements to React applications.

Example Code

import React, { useState } from 'react';
import Lottie from 'react-lottie';

// IMPORTANT: In a real application, you would import your Lottie animation JSON file like this:
// import animationData from './path/to/your/animation.json';
// For demonstration purposes, we're providing a very minimal, dummy JSON structure.
const sampleAnimationData = {
  "v": "5.7.4",
  "fr": 30,
  "ip": 0,
  "op": 90,
  "w": 200,
  "h": 200,
  "nm": "Minimal Example",
  "ddd": 0,
  "assets": [],
  "layers": [
    {
      "ddd": 0,
      "ind": 0,
      "ty": 4,
      "nm": "Shape Layer 1",
      "sr": 1,
      "ks": {
        "o": {"a": 0, "k": 100},
        "r": {"a": 0, "k": 0},
        "p": {"a": 0, "k": [100, 100, 0]},
        "a": {"a": 0, "k": [0, 0, 0]},
        "s": {"a": 0, "k": [100, 100, 100]}
      },
      "ao": 0,
      "ip": 0,
      "op": 90,
      "st": 0,
      "bm": 0,
      "shapes": [
        {
          "ty": "gr",
          "it": [
            {
              "ty": "sh",
              "pt": {"a": 1, "k": [
                {"i": [0.5, 0.5], "o": [0.5, 0.5], "t": 0, "s": [[0,0]], "e": [[20,0]]},
                {"i": [0.5, 0.5], "o": [0.5, 0.5], "t": 30, "s": [[20,0]], "e": [[0,20]]},
                {"i": [0.5, 0.5], "o": [0.5, 0.5], "t": 60, "s": [[0,20]], "e": [[-20,0]]},
                {"i": [0.5, 0.5], "o": [0.5, 0.5], "t": 90, "s": [[-20,0]], "e": [[0,0]]}
              ]},
              "nm": "Path 1",
              "ind": 0,
              "ks": {"a": 0, "k": {"i": [[-4.4,-0.4],[-0.2,-4.7],[4.4,0.4],[0.2,4.7]], "o": [[4.4,0.4],[0.2,4.7],[-4.4,-0.4],[-0.2,-4.7]], "v": [[0,-20],[20,0],[0,20],[-20,0]]}}
            },
            {"ty": "st", "c": {"a": 0, "k": [0,0,0,1]}, "o": {"a": 0, "k": 100}, "w": {"a": 0, "k": 2}, "lc": 2, "lj": 1, "ml": 4, "nm": "Stroke 1"},
            {"ty": "fl", "c": {"a": 0, "k": [1,0,0,1]}, "o": {"a": 0, "k": 100}, "r": 1, "nm": "Fill 1"},
            {"ty": "tr", "p": {"a": 0, "k": [0,0]}, "a": {"a": 0, "k": [0,0]}, "s": {"a": 0, "k": [100,100]}, "r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}, "sk": {"a": 0, "k": 0}, "sa": {"a": 0, "k": 0}, "nm": "Transform"}
          ],
          "nm": "Group 1"
        }
      ]
    }
  ]
}; 

function LottieAnimationPlayer() {
  // State to control animation playback
  const [isPaused, setIsPaused] = useState(false);
  const [isStopped, setIsStopped] = useState(false);

  // Default options for the Lottie animation player component
  const defaultOptions = {
    loop: true,        // Animation will loop indefinitely
    autoplay: true,    // Animation will start playing automatically
    animationData: sampleAnimationData, // The actual animation JSON data (replace with your imported JSON)
    rendererSettings: {
      preserveAspectRatio: 'xMidYMid slice' // How the animation fits into its container
    }
  };

  return (
    <div style={{ textAlign: 'center', padding: '20px', fontFamily: 'Arial, sans-serif' }}>
      <h1>React Lottie Example</h1>
      <p>Using <code>react-lottie</code> to display a Lottie animation.</p>

      <div
        style={{
          width: '300px',
          height: '300px',
          margin: '20px auto',
          border: '1px solid #ddd',
          borderRadius: '8px',
          boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
          overflow: 'hidden'
        }}
      >
        <Lottie 
          options={defaultOptions} 
          height={300} 
          width={300} 
          isStopped={isStopped} // Dynamically stop/play the animation
          isPaused={isPaused}   // Dynamically pause/resume the animation
          // Event listeners can be added to react to animation lifecycle events
          eventListeners={[
            {
              eventName: 'complete',
              callback: () => console.log('Animation playback completed!')
            },
            {
              eventName: 'loopComplete',
              callback: () => console.log('A loop of the animation has completed.')
            },
            {
              eventName: 'data_ready',
              callback: () => console.log('Animation data is ready to be played.')
            }
          ]}
        />
      </div>

      <div style={{ marginTop: '15px' }}>
        <button 
          onClick={() => setIsPaused(!isPaused)}
          style={{
            margin: '5px', 
            padding: '10px 20px', 
            fontSize: '1em', 
            cursor: 'pointer', 
            backgroundColor: '#007bff', 
            color: 'white', 
            border: 'none', 
            borderRadius: '5px'
          }}
        >
          {isPaused ? 'Resume' : 'Pause'}
        </button>
        <button 
          onClick={() => setIsStopped(!isStopped)}
          style={{
            margin: '5px', 
            padding: '10px 20px', 
            fontSize: '1em', 
            cursor: 'pointer', 
            backgroundColor: '#dc3545', 
            color: 'white', 
            border: 'none', 
            borderRadius: '5px'
          }}
        >
          {isStopped ? 'Play' : 'Stop'}
        </button>
      </div>

      <p style={{ marginTop: '25px', fontSize: '0.9em', color: '#555' }}>
        <em>Note: To run this code, ensure you have installed <code>react-lottie</code> via `npm install react-lottie` or `yarn add react-lottie`. Replace the `sampleAnimationData` with your actual Lottie JSON file imported into your component.</em>
      </p>
    </div>
  );
}

export default LottieAnimationPlayer;