How to create a custom loading component in Next.js



Image not found!!

Creating a custom loading component in Next.js involves a few steps. You can use a combination of React components, CSS, and state management to achieve this. Here's a basic example:

  1. Create a new component for your loader:

    Create a new file, for example, Loader.js in your components folder.

    jsx
    // components/Loader.js import React from 'react'; import styles from './Loader.module.css'; const Loader = () => { return ( <div className={styles.loader}> {/* Customize your loader here */} Loading... </div> ); }; export default Loader;
  2. Style your loader:

    Create a CSS module file (e.g., Loader.module.css) in the same folder as your Loader component.

    css
    /* components/Loader.module.css */ .loader { /* Add your styling for the loader here */ border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 50px; height: 50px; animation: spin 1s linear infinite; margin: 0 auto; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  3. Use the loader in your pages:

    Import and use the Loader component in the pages where you want to display the loading indicator.

    jsx
    // pages/index.js (or any other page) import React, { useState, useEffect } from 'react'; import Loader from '../components/Loader'; const MyPage = () => { const [loading, setLoading] = useState(true); useEffect(() => { // Simulate an asynchronous action const fetchData = async () => { // Assume your asynchronous action takes 2 seconds await new Promise(resolve => setTimeout(resolve, 2000)); setLoading(false); }; fetchData(); }, []); return ( <div> {loading ? <Loader /> : <p>Your content goes here</p>} </div> ); }; export default MyPage;

    In this example, the Loader component is displayed when the loading state is true, and once the asynchronous action (simulated with useEffect) is completed, the content is displayed.

  4. Customize the loader as needed:

    Adjust the styling and content of your loader according to your preferences.

Remember to install any necessary dependencies and configure your project if you're using CSS modules or other libraries for styling. This example provides a basic structure, and you can enhance it based on your project requirements.