How to implement a loading spinner in Next.js



Image not found!!

Implementing a loading spinner in Next.js involves creating a component that displays the spinner when data is being fetched or when a page is loading. Below is a simple example of how you can create a loading spinner in Next.js.

  1. Create a LoadingSpinner component:

    Create a new file called LoadingSpinner.js in your components folder:

    jsx
    // components/LoadingSpinner.js import React from 'react'; const LoadingSpinner = () => { return ( <div className="loading-spinner"> {/* Add your loading spinner animation or image here */} Loading... </div> ); }; export default LoadingSpinner;
  2. Use the LoadingSpinner component in your pages:

    In your pages where you want to display the loading spinner, import the LoadingSpinner component and conditionally render it based on whether data is being fetched or not. For example:

    jsx
    // pages/index.js import React, { useState, useEffect } from 'react'; import LoadingSpinner from '../components/LoadingSpinner'; const HomePage = () => { const [loading, setLoading] = useState(true); useEffect(() => { // Simulate fetching data const fetchData = async () => { // Set loading to true when starting to fetch data setLoading(true); // Simulate API call await new Promise(resolve => setTimeout(resolve, 2000)); // Set loading to false when data is fetched setLoading(false); }; fetchData(); }, []); return ( <div> <h1>Next.js Loading Spinner Example</h1> {loading ? <LoadingSpinner /> : <p>Data Loaded Successfully!</p>} </div> ); }; export default HomePage;
  3. Style the LoadingSpinner:

    You may want to add some CSS styles to make your loading spinner visually appealing. You can do this by adding styles to the loading-spinner class in the LoadingSpinner component.

    css
    /* styles/loadingSpinner.css */ .loading-spinner { display: flex; justify-content: center; align-items: center; height: 100px; /* Set a suitable height */ font-size: 20px; }

    Import this stylesheet in your LoadingSpinner.js file:

    jsx
    // components/LoadingSpinner.js import React from 'react'; import './styles/loadingSpinner.css'; const LoadingSpinner = () => { return ( <div className="loading-spinner"> {/* Add your loading spinner animation or image here */} Loading... </div> ); }; export default LoadingSpinner;

Now, when you navigate to your page, the loading spinner will be displayed while data is being fetched, and once the data is loaded, the spinner will be replaced with the actual content.