Frontend Development 11 min read

Implementing Switch Animations with Lottie in Frontend Development

This article explains how to use the Lottie library to replace hand‑written CSS/JS or GIF animations with vector‑based, cross‑platform switch animations, covering installation, configuration options, direction control, playback speed, JSON modification, and a helper function for updating values.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Implementing Switch Animations with Lottie in Frontend Development

During routine front‑end development, developers often need to create animation effects, which can be time‑consuming when written manually with CSS or JavaScript. This tutorial shows how to use Lottie to faithfully reproduce designer animations and improve efficiency.

Introduction to Lottie

The article first compares common animation methods—CSS animations, JavaScript animations, GIFs, and Lottie—listing their advantages and disadvantages in a table.

Animation Type

Pros

Cons

CSS Animation

Simple to use with

@keyframes

and

transition

; native browser support; good performance

Limited control; verbose for complex animations

JavaScript Animation

High control and flexibility; suitable for complex effects

Additional libraries increase bundle size; learning curve; possible performance impact

GIF Animation

Easy to create and use; universally supported

Limited color depth; larger files for higher quality; not resolution‑independent

Lottie

Vector‑based, retains clarity and smoothness; cross‑platform (iOS, Android, Web)

May affect performance on older/low‑end devices; requires designer cooperation

Lottie is an open‑source library developed by Airbnb that renders animations exported from After Effects as JSON Bodymovin files. Compared with hand‑written CSS/JS or GIFs, it reduces development effort and keeps file size small while preserving quality.

Hello Lottie

Assuming a Lottie JSON file is available, install the required dependencies:

npm i react-lottie prop-types

Then import and render the animation:

import animationData from "../../assets/switch-lottie.json";

const LottieSwitch = () => {
  const playing = useRef(false);
  const options = {
    loop: true,
    autoplay: true,
    animationData,
    rendererSettings: { preserveAspectRatio: "xMidYMid slice" },
  };
  return (
);
};

Options Explanation

loop : whether the animation repeats.

autoplay : whether it starts automatically.

animationData : the JSON animation resource.

rendererSettings.preserveAspectRatio : how the animation scales inside its container (e.g., xMidYMid centers horizontally and vertically).

Forward / Reverse Playback

By toggling the direction field (1 for forward, -1 for reverse) you can create a switch effect. The implementation includes:

Click to toggle direction.

Lock playback while the animation is running.

Listen for the complete event to unlock.

Set loop and autoplay to false for manual control.

const LottieSwitch = () => {
  const [direction, setDirection] = useState(null);
  const playing = useRef(false);
  const options = { loop: false, autoplay: false, animationData, rendererSettings: { preserveAspectRatio: "xMidYMid slice" } };

  const handleClick = () => {
    if (playing.current) return;
    playing.current = true;
    setDirection(prev => (prev === 1 ? -1 : 1));
  };

  return (
{ playing.current = false; } }]}
        />
);
};

Animation Duration

The JSON fields fr (frame rate), ip (in‑point), and op (out‑point) determine duration: (op‑ip)/fr . For a 30 fps animation from frame 0 to 60, the length is 2 seconds. To play it in 500 ms, set speed to 4.

<Lottie direction={direction} options={options} speed={4} height={20} width={40} />

Modifying Lottie JSON

Colors are stored in the "c" (color) property as RGBA arrays. To change a color, convert the RGB values to a 0‑1 range (e.g., rgb(99,102,241) → [99/255,102/255,241/255,1] ) and locate the corresponding node in the JSON.

A helper function updateJsonValue recursively finds a target value and replaces it:

const updateJsonValue = (json, targetValue, newValue) => {
  const find = (obj, target, path = []) => {
    for (const key in obj) {
      if (obj[key] === target) return [...path, key];
      if (typeof obj[key] === "object" && obj[key] !== null) {
        const result = find(obj[key], target, [...path, key]);
        if (result) return result;
      }
    }
  };
  const copy = JSON.parse(JSON.stringify(json));
  const path = find(copy, targetValue);
  let cur = copy;
  for (let i = 0; i < path.length - 1; i++) cur = cur[path[i]];
  cur[path[path.length - 1]] = newValue;
  return copy;
};

Using this function you can replace the original color values with new ones (e.g., change to rgb(25,195,125) ) by providing the appropriate target and new values.

Conclusion

The guide demonstrates how to integrate Lottie animations into a React front‑end project, control playback direction, adjust speed, and programmatically edit the underlying JSON to customize colors, text, or assets, offering a powerful alternative to manual CSS/JS or GIF animations.

frontendanimationLottieJavaScriptreactJSON
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.