How to implement a custom loading spinner with Lottie animations in Next.js



Image not found!!


To implement a custom loading spinner with Lottie animations in Next.js, you can follow these steps:

  1. Install Dependencies: First, you need to install the required dependencies. You'll need lottie-web and react-lottie.
bash
npm install lottie-web react-lottie
  1. Create Your Lottie Animation: You can create or download a Lottie animation file (.json format). There are several websites where you can find free or paid Lottie animations, such as LottieFiles (https://lottiefiles.com/).

  2. Place the Animation File: Place your Lottie animation file in the public directory of your Next.js project. For example, if your animation file is named loading.json, you would place it in public/loading.json.

  3. Create a Component: Create a React component for your loading spinner. This component will use react-lottie to render the Lottie animation.

jsx
// components/LoadingSpinner.js import React from 'react'; import Lottie from 'react-lottie'; import animationData from '../public/loading.json'; // Path to your Lottie animation file const LoadingSpinner = () => { const defaultOptions = { loop: true, autoplay: true, animationData: animationData, rendererSettings: { preserveAspectRatio: 'xMidYMid slice' } }; return <Lottie options={defaultOptions} height={120} width={120} />; }; export default LoadingSpinner;
  1. Use the Component: You can now use the LoadingSpinner component wherever you need it in your Next.js application. For example, you might use it as a loading indicator while data is being fetched.
jsx
// pages/index.js import React, { useState, useEffect } from 'react'; import LoadingSpinner from '../components/LoadingSpinner'; const IndexPage = () => { const [loading, setLoading] = useState(true); useEffect(() => { // Simulate data fetching const timer = setTimeout(() => { setLoading(false); }, 3000); return () => clearTimeout(timer); }, []); return ( <div> {loading ? ( <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}> <LoadingSpinner /> </div> ) : ( <div> {/* Content when loading is complete */} </div> )} </div> ); }; export default IndexPage;
  1. Styling: You can add CSS to style the loading spinner as needed.

That's it! You've now implemented a custom loading spinner with Lottie animations in your Next.js application. Adjust the animation file, size, and other options as needed to fit your design requirements.