1.

What are keys and its significance in Listing

Answer»

Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity

The best way to pick a KEY is to use a string that uniquely identifies a list item among its SIBLINGS. Most often you would use IDs from your data as keys

Keys used within arrays should be unique among their siblings. However they don’t need to be globally unique. We can use the same keys when we produce two different arrays

To understand this you need understand how the VIRTUAL DOM works in React. The virtual DOM (VDOM) is a programming concept where an IDEAL, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.

Each time the underlying data changes in a React app, a new Virtual DOM representation of the USER interface is created Updating browser DOM is as follows

  1. Whenever anything may have changed, the entire UI will be re-rendered in a Virtual DOM representation.
  2. The difference between the previous Virtual DOM representation and the new one will be calculated.
  3. The real DOM will be updated with what has actually changed. This is very much like applying a patch.

Look at the example given below

import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; class App extends React.Component { render() { const numbers = [1,2,3,4,5]; const listItems = numbers.map((number) => <li> {number} </li> ); return ( <div className="App"> <h2>Hellow World!!</h2> <div>{listItems}</div> </div> ); } } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);

This will throw a warning in console

  • Warning: Each child in an array or iterator should have a unique "key" prop.
  • To fix it we should change the arrow function “listItems” to
const listItems = numbers.map((number) => <li key={number.toString()}> {number} </li> );


Discussion

No Comment Found