Search code examples
reactjslottieastrojsstatic-site-generation

how to use lottie-react in astro build framework


I was trying astro build and want to use lottie json files for animations, but there is no documented resource that describe how can we use lottie-react in astro build framework.

I try lottie-react npm package everything works fine in dev, but when i try to build it throw and error as we can not generate static content from lottie-react library.

Is this even possible to use lottie-react in astro, if yes ? then please explain in detail!


Solution

  • First some references

    Steps I used to recreate the example other steps possible too

    npm create astro@latest -- --template minimal
    
    • enter directory name
    • don't install dependencies
    • typescript relaxed
    pnpm install
    npx astro add react
    

    This does not work

    a simple and direct integration on the same page does not work index.astro

    ---
    import Lottie from "lottie-react";
    import groovyWalkAnimation from "../lottie/groovyWalk.json";
    ---
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <meta name="viewport" content="width=device-width" />
            <title>Astro</title>
        </head>
        <body>
            <h1>Astro</h1>
            <Lottie animationData={groovyWalkAnimation} loop={true} client:load/>
        </body>
    </html>
    

    This is how it works

    it works when placing lottie-react on a .jsx file Lottie.jsx which is taken from here https://www.npmjs.com/package/lottie-react section (Using the Hook)

    import React from "react";
    import { useLottie } from "lottie-react";
    import groovyWalkAnimation from "../lottie/groovyWalk.json";
    
    const App = () => {
      const options = {
        animationData: groovyWalkAnimation,
        loop: true
      };
    
      const { View } = useLottie(options);
    
      return <>{View}</>;
    };
    
    export default App;
    

    index.astro

    ---
    import Lottie from './Lottie';
    ---
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
            <meta name="viewport" content="width=device-width" />
            <meta name="generator" content={Astro.generator} />
            <title>Astro</title>
        </head>
        <body>
            <h1>Astro</h1>
            <Lottie client:load/>
        </body>
    </html>
    

    Working example