0

I am coding a simple app and I wanted to add Page Transitions using framer-motion library. The problem that I'm facing is that every tutorial and documentation that I see, uses the <motion.div> tag inside each component, which I find kind of annoying.

This is the return of my App.js

return (
<Router>
  <div className="App">
    <Switch>
      <Route exact path="/">
        <HomeScreen />
      </Route>
      <Route exact path="/contact">
        <ContactScreen />
      </Route>
      <Route exact path="/aboutus">
        <AboutUsScreen />
      </Route>
    </Switch>
  </div>
</Router >

);

If I would want to add the animation, I'd have to add <motion.div> inside each component. What I'm looking to do (and not being able to make it work) is something like this:

      <Route exact path="/">
        <motion.div initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
        >
          <HomeScreen />
        </motion.div>
      </Route>

I've been stuck at this since last week. If someone could give me a hand with this, I'd be really grateful!

1 Answers1

0

So, if I understood correctly, then you can do something like this:

1st: Create a custom component like the one below

import React from "react";
import { motion } from "framer-motion";

interface IProps {
  initial: {};
  animate: {};
  children: any;
  transition: {};
  component: string;
  className: string;
  exit?: {}; // can be undefined
}
const AnimatedFramerMotionComponent = ({
  exit,
  initial,
  animate,
  children,
  component,
  className,
  transition,
}: IProps) => {
  const CustomComponent: any = motion(component);

  return (
    <CustomComponent
      initial={initial}
      animate={animate}
      exit={exit}
      transition={transition}
      className={className}
    >
      {children}
    </CustomComponent>
  );
};

export default AnimatedFramerMotionComponent;

2nd: Use it like this

<AnimatedFramerMotionComponent
    component="h1"
    initial={{ y: "-100%", opacity: 0 }}
    animate={{ y: 0, opacity: 1 }}
    transition={{ delay: 1 }}
    className="text-white text-8xl"
  >
    Regenci
  </AnimatedFramerMotionComponent>
Esc Official
  • 99
  • 10