Home > Net >  use react component instead of motion's elements in Framer motion
use react component instead of motion's elements in Framer motion

Time:10-01

Hi I have a component like this :

const Comp = (props) => {
    return(
       <div>
           data here
       </div>
    )
}

and I want to use framer motion like this:

const Container = () => {
    return(
       <motion.Comp variants={variants} someProp="someProp"/>
    )
}

The reason I want to do this is that I don't think making a lot of div as a wrapper is a great idea. I could use motion.div in "Comp" component but some of my app component is made that I don't need animating all of them in my whole app. I just want a solution to add animations to the first element in the component.

Also I searched and I found a solution "motion(Comp)", but it's not working.

CodePudding user response:

From the docs (https://www.framer.com/docs/component/#custom-components), you can wrap any component with motion() to use it as if it were a framer-motion component. You mentioned that you found that solution but that it's not working, and without any more details about it I can't give you a specific reason why. But most likely you're forgetting to pass the ref through to your component, like this:

const Foo = React.forwardRef((props, ref) => <div ref={ref} />)

The ref is the way that framer-motion will identify which element on the page is the one it should be animating, so it needs to be passed to the correct element. Once that's done, you can wrap it with motion:

const MotionFoo = motion(Foo)

Keep in mind that regardless of how many elements your custom component has, only the one that has the ref passed to it will be animated. For example:

const BusyFoo = React.forwardRef((props, ref) => (
  <div>
    <div ref={ref}>I will be animated!</div>
    <div>I won't be animated. :(</div>
  </div>
)
  • Related