14 List Rendering - biswajitsundara/react GitHub Wiki
Lists are used to display data in an ordered format and in react we can implement this.
- We traverse the list and render each list item
- The java script
map()
array method is used to iterate through the array
Lets say we have a list of names to be displayed.
const ListItem = () => {
const names = ["Kareena", "Anushka", "Alia"];
return (
<div>
{names.map((name) => {
return <h1 key={name}>{name}</h1>;
})}
</div>
);
};
export default ListItem;
React looks for a key
attribute when we render list of items.
- The
key
attribute should be unique. - It doesn't impact any thing on the UI, react needs this to manage the content internally.
- During filtering, sorting the key attribute is used by react.
- Usually the id, or any unique value is used in keys
- E.g in the above example name is unique so we have used that - return <h1 key={name}>{name}</h1>;
- If we don't declare the key attribute then there will be console errors.