DEV Community

Aditya
Aditya

Posted on

Need help in React Page transition

The page transition is not happening as expected, the navigation component is rendering before the animation begins. How can I avoid this. Please suggest

const loginRouter = createBrowserRouter([
  { path: "/login", element: <Login /> },
  {
    path: "/home",
    element: (
      <Transition>
        <Profile />
      </Transition>
    ),
    errorElement: <SomethingWrong />,
    children: [
      {
        index: true,
        element: (
          <Suspense fallback="loading">
            <Home />
          </Suspense>
        ),
        loader: moviesList,
        errorElement: <NotFound />,
      },
       {
        path: ":category",
        loader: fetchAllMoviesFromCategory,
        element: (
          <Suspense fallback="loading">
            <ListOfMovies />
          </Suspense>
        ),
      },
    ],
  },
]);
function App() {
  console.log("App.js");
  return <RouterProvider router={loginRouter} />;
}
Enter fullscreen mode Exit fullscreen mode

Transition.js

const transitionVariants = {
  initial: {
    opacity: 0,
  },
  animate: {
    opacity: 1,
    transition: { duration: 0.5, delay: 0.7 },
  },
  exit: {
    opacity: 0,
    transition: { duration: 0.5 },
  },
};

function Transition({ children }) {
  const location = useLocation();
  return (
    <AnimatePresence mode="wait">
      <motion.div
        key={location.pathname}
        variants={transitionVariants}
        initial="initial"
        animate="animate"
        exit="exit"
      >
          {children}
      </motion.div>
    </AnimatePresence>
  );
}

export default Transition;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)