Wednesday, November 20, 2024
Google search engine
HomeLanguagesWhat are keys and its significance in Listing in ReactJS ?

What are keys and its significance in Listing in ReactJS ?

Keys in ReactJS 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 keys that are unique.

React uses these keys to create a relationship between the DOM element and the component. It determines whether the component should be rendered or not. The unique identity is given to the element which helps to get a track of particularly which element in the DOM has been updated, removed, or added.

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>)
})}

The below example will illustrate the use of keys in React.

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

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.

Using the key property: 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.

App.js




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


Console Log: Now, we can see no more errors in the console.

However, this is not an ideal way of defining the key as an array with duplicate elements will assign duplicate keys and it would throw an error. For example, using the below array as keys, we will get the following output.

const num = [1,2,3,4,1];

Console Log: It will show the error that two children have the same keys.

Using the index of the map function as keys: 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.

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:

An ideal solution: In the case of a dynamic list, where it may be filtered or reordered, the above approach will not work properly leading to unstable component behavior. If you already have a unique id mentioned in the list to be displayed, you can always use that as your key. This is the preferred way how the list should be rendered as these unique ids will help React to understand the ordering of the elements.

Example: Let’s suppose an example of an array of colors that are having some ids that we will be using as our keys.

App.js




const colors = [
    {
        id: 1,
        value: "red"
    }, {
        id: 2,
        value: "green"
    }, {
        id: 3,
        value: "black"
    }
];
  
function App() {
    return (
        <div className="App">
            <ul>
                {colors.map(item => {
                    return (
                        <option key={item.id}>
                            {item.value}
                        </option>
                    )
                })}
            </ul>
        </div>
    );
}
  
export default App;


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments