Working with lists and keys in React.js


Displaying a list on UI in React

Map is JavaScript function which will return a new array for provided array as shown below −

const originalNumbers = [ 2, 4, 6, 8, 10];
const squaredNumbers = originalNumbers.map( (number)=> number * number);
console.log(“Squared Numbers==”squaredNumbers);

Building a list in React is similar with the use of map function. Instead of just returning a square number , we will return a list element with value of square.

const originalNumbers = [ 2, 4, 6, 8, 10];
const squaredNumbersList= originalNumbers.map((number) =>
   <li>{number*number}</li>
);

Render on the screen with ui tag −

ReactDOM.render(
   <ul>{ squaredNumbersList }</ul>,
   document.getElementById('root')
);

When we run this example, we will receive a warning in browser console saying key is missing for list. For react to understand each row it needs a key which should be unique to row.

const squaredNumbersList= originalNumbers.map((number) =>
   <li key={SomeUniqueKey}>{number*number}</li>
);

Keys will be used in identifying which row is changed or removed or added newly. Accordingly React will update the UI. We will get the index of loop as well.

const squaredNumbersList= originalNumbers.map((number,index) =>
   <li key={index}>{number*number}</li>
);

But React does not recommend using index as key as it has some negative impacts on performance of application.

Keys should be unique among the sibling rows and not needed to be globally unique in component.

The element inside the map function needs the key and not the other nested children elements in row.

Embedding map function in jsx expression −

function MessageList(props) {
   const messages = props.messages;
   return (
      <ul>
         {messages.map((message) =>
            <ListItem key={message.rowKey}
               value={message.text} />
         )}
      </ul>
   );
}

Here ListItem is a custom component taking each message as value prop and key is rowKey on the message object.

Its good practice to use a separate component if list is big and writing a clean code.

Updated on: 28-Aug-2019

396 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements