To implement a custom loading spinner with Lottie animations in Next.js, you can follow these steps:
lottie-web
and react-lottie
.bashnpm install lottie-web react-lottie
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/).
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
.
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;
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;
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.