skip to Main Content

I have set up a sandbox to illustrate my problem: Link to codesandbox

When you click ‘All’ and then a year, it doesnt animate the boxes. It also skips animating the other way around on the elements from a specific year. If you click a year and then ‘All’. Only new elements are animated.

How could I solve this with framer-motion?

I have tried using the key propery on the <motion.div> element but without any success.

2

Answers


  1. Chosen as BEST ANSWER

    I figured it out. What I needed was to put layout prop on the <motion.div. You can read more about it here: layout animations

    I updated my codesandbox with that prop. You can view the working codesandbox here: Working sandbox


  2. You should try adding <AnimatePresence> with some additional props. Here is an example link to codeSandbox

    export default function App() {
    const [persons, setPersons] = useState(arr);
    
    function handleChange(e) {
      // ...
    }
    
    return (
      <>
    ...
    ...
        <div style={{ display: "grid", gap: "1rem", justifyItems: "center" }}>
          <AnimatePresence>
            {persons.map((person) => (
              <Person name={person.name} year={person.year} key={person.name} />
            ))}
          </AnimatePresence>
        </div>
      </>
    );
    }
    

    Animation Properties for <motion.div>

    const itemAnimation = {
      initial: { opacity: 0, scale: 0.2 },
      animate: { opacity: 1, scale: 1 },
      transition: { duration: 1 },
      exit: { opacity: 0, scale: 0 }
    };
    

    Your Each Array item div should look like

    function Person({ name, year }) {
      return (
        <motion.div
          key={name + year}
          className="motion-div"
          variants={itemAnimation}
          initial="initial"
          animate="animate"
          exit="exit"
        >
          <p>
            {name} - {year}
          </p>
        </motion.div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search