Animate Components On Exit With Framer Motion React

Viewed 299

I have a button that toggles between two components. How do I add an animation for each component on exit? Here is my code that doesn't work:

export default function App() {
  const [dark, setDark] = useState(false);
  const toggle = () => {
    setDark(!dark);
  };

  return (
    <div>
      <AnimatePresence>
        {dark ? (
          <motion.h2 exit={{ opacity: 0 }}>Dark</motion.h2>
        ) : (
          <motion.h2 exit={{ opacity: 0 }}>Light</motion.h2>
        )}
      </AnimatePresence>
      <button onClick={toggle}>Toggle</button>
    </div>
  );
}

Thanks for your help!

1 Answers

This is fixed now. In order for animation to work, you should add initial and animate props. Also each component needs to have a unique key.

Related