How to use the index of the map function as keys In ReactJS

We can also pass the indices of the elements that are provided by the map function as the keys of the list items. This will eliminate the case where the items themselves are not distinct.

Javascript




// App.js
 
const num = [1, 2, 3, 4, 1];
 
function App() {
    return (
        <div className="App">
            <ul>
                {num.map((item, index) => {
                    return (
                      <option key={index}>
                          {index} > {item}
                      </option>)
                })}
            </ul>
        </div>
    );
}
 
export default App;


Output:

What are keys and its significance in Listing in React JS ?

Keys in React JS help to identify which items in the list have been changed, are removed, or are added. Keys are used as props to our map operator while iterating the list. We cannot use keys in React as props to the child component. It is mostly recommended to use Strings as unique keys.

Below are the different ways to use keys let’s see:

Table of Content

  • Using the key property
  • Using the index of the map function as keys
  • An ideal solution

Syntax: We are using a map operator to iterate a list that is returning the items.

{list.map((item => {
return (<li key="key">{item}</li>)
})}

Example: We will start by constructing simple array nums and then we are iterating over it.

Javascript




// App.js
 
const num = [1, 2, 3, 4];
 
function App() {
    return (
        <div className="App">
            <li>
                {num.map(item => {
                    return (
                        <option>{item}</option>
                    );
                })}
            </li>
        </div>
    );
}
 
export default App;


Console Log: We will see errors, asking for unique keys so that it becomes easier to know which element has been edited or changed, or removed.

Similar Reads

Using the key property:

...

Using the index of the map function as keys:

Now, we will add the key property to the list of items. We can use the item themselves as the keys as the array contains distinct elements hence it will not be a problem....

An Ideal Solution:

...