Search code examples
reactjsanimationframer-motion

how to tell react to run framer motion unmount animate when re-render


I'm creating a sidebar which contains some items and some of the items contain sub-items here is my demo: https://codesandbox.io/s/framer-motion-sidebar-effect-mfkpsl?file=/src/SidebarListItem.jsx

now the opacity and blur animation only runs when I hover Home and then About/Contact (from sub-items container -> non-(subitems container) or vice versa)

what I want to acheive is run the animation even when I switch from About to Contact (About and Contact both contain sub-items)

if 2 items also contains sub-item it won't trigger unmount of the sub-list how I could do it? Thanks!!


Solution

  • You're using this motion.ul to contain the submenu for the hovered section:

    <motion.ul
      variants={subMenuVariant}
      className="absolute top-0 right-0 pr-10 translate-x-[115%]"
    >
      {navLinks
        .filter((item) => item.link === currentHover)[0]
        .sublinks.map((link, i) => (
          <li
            key={i}
            className="py-1.5 text-[1.8rem] select-none cursor-pointer"
          >
            {link}
          </li>
        ))}
    </motion.ul>
    

    Since only the child elements are changing (the lis), Framer treats the ul as the same unchanging container element. So it doesn't animate in and out as the content changes.

    You need to set a unique key on the container element (motion.ul) so Framer knows the element changed. Otherwise it thinks you intend that element to remain the same and it won't trigger the animation.

    You can use your currentHover variable since that value changes when your hover target changes:

    <motion.ul
        key={currentHover}
        variants={subMenuVariant}
        className="absolute top-0 right-0 pr-10 translate-x-[115%]"
    >