Why should I use key as string for list item in React?

Viewed 964

React Doc explains why giving a key to list item is important. It specifies that a key is string attribute.

So should I convert my id to string for key every time?

<ul>
  {data.map(item => (
    <li key={item.id.toString()}>
      {item.text}
    </li>
</ul>

Could you tell me the reason for this? I thought about problem with number sort as strings but it seemed to be another case.

React Doc. List and Keys

2 Answers

Key is fundamental for the React to index a list in the render process (in the background). If you don't put the key, you get this:

enter image description here

This simply means that he needs to look for the component, what will take longer.

To solve the toString(), to this:

key={`OperationTesterInput_${idx}`

Looks much more cleaner. You can also use the index parameter present in the map function, also does the trick :)

The Reason why its a string

It is not. The reason is because of typescript. The implementation is the following:

enter image description here

So following this implementation, this is valid:

enter image description here

Generally, Key is used so that if an element changes or is removed, React only needs to rerender that specific element rather than the whole list. This key is required to be a string because the HTML attribute values are always strings, whatever value you give must be serialized to a string. We can assign anything to an attribute, but it becomes a string.

Related