How To Render Lists And Keys In React? See Example

Lists in React are created by using JavaScript’s map() function to iterate over an array and render components dynamically.

Example:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) => <li>{number}</li>);

function NumberList() {
  return <ul>{listItems}</ul>;
}

Importance of Keys

Keys are unique identifiers for elements in a list. They help React efficiently update and re-render items when the list changes.

Example with keys:

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) => <li key={number}>{number}</li>);

Rules for Using Keys

  • Keys should be unique among siblings
  • Prefer stable IDs from data instead of array index
  • Don’t use random numbers as keys, it can reduce performance

Rendering Components in a List

You can also render custom components in a list:

function User({ name }) {
  return <li>{name}</li>;
}

const users = ["Amit", "Sagar", "Priya"];
const userList = users.map((user) => <User key={user} name={user} />);

function UserList() {
  return <ul>{userList}</ul>;
}

Conclusion

Lists and keys are crucial for rendering dynamic data in React. Proper usage improves performance, stability, and predictability of your UI.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *