0

I'm building a UI where there is a list of items. When the user adds an item, it will send an API request to create a new item, but it will also add the item to the list with a temporary ID. Once the API comes back, it will replace the ID of the item with the actual ID from the backend. The problem is that when I change the key of the item in the list, react-transition-group will treat it as a deletion/addition and trigger an animation.

Here's my question: How can I tell react-transition-group that the new ID belongs to the old item, so it doesn't trigger an update?

Isaac
  • 213
  • 2
  • 10
  • You're more likely to get quick assistance if you provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).. at the very least supply some of your code and how you're using it, etc... Help others, help you. – Matt Oestreich Oct 09 '19 at 23:25

1 Answers1

0

I am not very familiar with react-transition-group, but I made transition with other libraries. I think you you use the id as a key now. I would add a key field to my object in the array. The key should be unique. You can make it unique multiple way for example with a counter or uuid. I like uuid. This way if you change the temporal id to the final one and the key remains the same then there will be no animation.

const [items, setItems] = useState([
  { key: uuid(), id:'temporal id', name: 'name' },
  ...
]);

In the transition use the key, instead of the id.

<TransitionGroup className="todo-list">
  {items.map(({ key, name }) => (
    <CSSTransition
      key={key}
      timeout={500}
      classNames="item"
    >
Peter Ambruzs
  • 7,763
  • 3
  • 30
  • 36
  • I was hoping there was a way to do it without having to keep track of all the ids, but it looks like that's the only way to do it. – Isaac Oct 14 '19 at 19:44