Search code examples
reactjsframer-motion

Apply styles to child element on parent hover (framer motion)?


i saw this code and i took a screenshot and tried it but it didnt work
is this even a thing or not ?

enter image description here


Solution

  • When animation property (like animate or whileHover) defined as string (i.e. variant), it's value is 'propagated' to children by default. So you can define variants on children and whileHover on parent and framer motion will animate children when its parent is hovered. You can find more (with examples) in framer motion documentation.

    So, for example, if you want to animate h2 when section is hovered you can do it like this:

    const variants = {
        hover: { scale: 1.2 },
    };
    
    const Example = () => {
        return (<motion.section whileHover="hover">
            <motion.h2 variants={variants}>Title...</motion.h2>
            <motion.div>Lorem ipsum dolor sit amet</motion.div>
        </motion.section>);
    };