Search code examples
reactjsnext.jsframer-motion

How to add fullscreen loader only when refreshing page and page fade page transitions in NextJS


I want to add a fullscreen loader to my Next.JS app to appear only when refreshing a page or loading it for a first time. It should not appear when routing between different pages. Also, I'd like to add fade transition when navigating between pages, like here https://www.vidstack.io/. How can I do that in Next.JS? Here is the example of the fullscreen loading I'd like to implement (https://stackblitz.com/edit/stackblitz-starters-vj4saw?file=app%2Flayout.tsx). Maybe it's possible to do with framer-motion?


Solution

  • You can do transition effects by using the framer-motion library for React. Here is a simple example:

    import { motion } from "framer-motion";
    
    export default function PageTransition({ children }) {
      return (
        <motion.main
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ duration: 1 }} // Adjust the duration as needed
        >
          {children}
        </motion.main>
      );
    }
    

    Usage:

    "use client"
    import PageTransition from "@/components/PageTransition";
    import React from 'react'
    
    export default function SimplePage() {
      return (
        <>
          <PageTransition>
            <main className="text-center uppercase">
              <p>
                Text.
              </p>
            </main>
          </PageTransition>
        </>
      )
    }