-1

How can I generate custom IDs for input without using any packages/moduls outside of React?

I found this example for unique keys using index, but as one user pointed out, while React documentation says you can do it that way:

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

It's not wise to use index for this. Is there any other way I could generate unique IDs with React? Thanks!

hemoglobin
  • 761
  • 4
  • 12
  • 33

1 Answers1

0

In the react docs you link it's says: "We don’t recommend using indexes for keys if the order of items may change."

So if you change the orders in your array (like sorting them) and you haven't a unique propertie just give them one initial (when you create the array or directly after getting the array)

todos.forEach((todo, index) => todo.index = index);
julian libor
  • 1,583
  • 1
  • 9
  • 8