1

When using react-spring it is possible to animate items as they are added / removed from an array. Now, I have an array with a fixed length where all items are null by default. When a value changes to an object, I fade in the component.

This works fine except when changing the value back to null. When unmounting, react-spring duplicates the component untill the animation of the original component is finished.

Is there a way to keep this duplicating from happening?

I made an example at https://codepen.io/AndriesVDW/pen/OJErMjv

<div id="app"></div>
.tiles {
  display: flex;
  gap: 10px;
  list-style: none;
  margin: 10px;
  padding: 0
}

.tile {
  height: 100px;
  width: 100px;
  border: 1px solid black;
  border-radius: 10px;
}

.card {
  height: 100%;
  width: 100%;
  background: red;
  border-radius: 10px;
}
const { useState } = React;
const { createRoot } = ReactDOM;

const { animated, useTransition } = ReactSpring;

const App = () => {
  return (
    <div>
      <Grid />
    </div>
  );
};

const Grid = () => {
  const [items, setItems] = React.useState([null, null, null]);

  const transition = useTransition(items, {
    from: { opacity: 0, transform: "translateY(-50px)" },
    enter: { opacity: 1, transform: "translateY(0px)" },
    leave: { opacity: 0, transform: "translateY(-50px)" }
  });
  
  const add = () => {
    setItems(["Card 1", null, null]);
  };

  const remove = () => {
    setItems([null, null, null]);
  };
  
  return (
    <div>
      <button onClick={ add }>Add card to first slot</button>
      <button onClick={ remove }>Remove card in first slot</button>
      <ul className="tiles">
        { transition((style, item) => (
          <li className="tile">
            { item && (
              <animated.div className="card" style={ style }>{ item }</animated.div>
            ) }
          </li>
        )) }
      </ul>
    </div>
  );
};

const container = document.getElementById('app');
const root = createRoot(container);

root.render(<App />);
Andries
  • 91
  • 9

0 Answers0