How to Set a Dynamic Key in React Using SetState

Using dynamic keys in React is quite simple.

All you need to do is wrap the key in square brackets.

Let’s look at a quick snippet from an example to see what this looks like:

The function takes in an `id` as an input.

It then invokes setState and uses that id as a key by wrapping it in square brackets.

So for example, if the function was passed `item1` as an id, this is equivalent to saying:


      item1: true


This won’t come up too often, but I’ll go over a complete component using the above function.

Example: SetState With a Dynamic Key

This is still a simplistic example, but should illustrate the types of situations you may need to set a dynamic key.

This component consists of 3 divs. When each div is clicked, it sets the state for the div’s id to true.

If the state’s id value is true, the div gets a special “highlighted” class.

If you didn’t have the square brackets, this won’t work. It would just give the state an `id` property with a value of true.