Rendering lists of data efficiently is a core part of React. React lets you loop through arrays and display elements using the map()
method. Each item in a list requires a unique key attribute to help React identify which items have changed, added, or removed.
map()
You can create an array of elements by transforming an array of data. Hereβs a simple example rendering a list of fruits:
const fruits = ['Apple', 'Banana', 'Cherry']; function FruitList() { return ( <ul> {fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))} </ul> ); }
Keys help React track which items have changed, so it can efficiently update the UI without re-rendering the entire list. A good key is:
If your data items have unique IDs, use those as keys instead of indices:
const todos = [ { id: 1, text: 'Learn React' }, { id: 2, text: 'Build Projects' }, { id: 3, text: 'Get Job' } ]; function TodoList() { return ( <ul> {todos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> ); }
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!