PresentationInteractive, narrated presentation of the section content.
Code ExampleInteractive coding exercise.
No problems found.
Code ExampleInteractive coding exercise.
No problems found.
Code ExampleInteractive coding exercise.
No problems found.
ContentDetailed description of the section content.
Rendering lists in React is a common task, as it allows developers to display dynamic data sets efficiently. This chapter will explore how to render lists, manage keys, and handle various data types.
Basics of Rendering Lists
React uses JSX to write HTML-like code inside JavaScript. When you have an array of data, and you want to display it, you'll likely need to convert each array item into a React element.
Using the map() Function
The simplest way to render a list in React is by using the JavaScript array map() function, which transforms each item in the array into a React element.
Example:
Pretty simple, huh? But wait! There is an error in your Javascript console saying Each child in a list should have a unique “key” prop. Let's fix that!
🔑 Keys in Lists
Understanding Keys
Keys are a crucial concept when rendering lists in React. They help React identify which items have changed, are added, or are removed. This helps in efficient updates of the user interface.
Guidelines for Keys:
Use a unique identifier for each element as a key.
Avoid using indices as keys if the order of items may change, which can negatively impact performance and component state management.
The simplest way to fix this is to use the “index” parameter of the map function. Thus the following statement:
numbers.map((number) => <li>{number}</li>)becomes the following:
numbers.map((number, index) => <li key={index}>{number}</li>)Let's check it out!
Voila. No errors!
But, using array indices as keys is not considered a good practice, particularly if you are able to modify the array elements. We will show you an example of when it fails soon, but first let's consider an alternative. A better practice for using keys is to use unique ids. Consider the following example:
const todos = [{ id: 1, text: "Some Todo" }, { id: 2, text: "Other Todo }];
function ToDoList({ todos }) {
return (
<ul>
{todos.map((todo) => <li key={todo.id}>{todo.text}</li>)}
</ul>
);
}
// Usage
const todos = [{id: 1, text: "Throw garbage"}, {id: 2, text: "Read book"}];
function App() {
return <ToDoList todos={todos} />;
}
export default App;In this example, we used the item's ID as a key of component rendered in the array. This will work much better, but make sure that those keys are unique, otherwise you can receive an error such the one below.

Now, we are ready for an example. Below, try typing anything in the first input in both Dangerous and Better sections. Once you click on “Add Item” button, the top input group will fail to render correctly, while the bottom one renders just fine. The problem is, that React did not correctly identify how the elements changed, as for React, the first element has the same key (0) as the newly inserted element.
If this all sounds too complex, just make sure that you do not use indices and that you always use unique IDs as you can encounter issues such as the one below!
Best Practices
Always use keys when rendering lists.
Keep components small and focused; let list items be rendered by a dedicated component if they are complex.
Common Mistakes
Using indices as keys in arrays where the order or items can change.
Forgetting to handle cases where the list might be empty or data might not be immediately available due to asynchronous loading.
Handling Empty Lists
If you want to display a message when the list is empty, you can use the length property.
function ArticleList({ articles }) {
if (!articles.length) {
return <p>No articles available.</p>;
}
return (
<ul>
{articles.map((article) => <li key={article.id}>{article.title}</li>)}
</ul>
);
}
// Usage
function App() {
return <ArticleList articles={[]} />;
}Handling Fragments in Arrays
Some times you may wish to render array elements without the root element. You can use fragments for this purpose, but the shorthand notation <></> will not work:
function ArticleList({ articles }) {
return (
<>
{articles.map((article) => (
<key={article.id}>{article.title}</> // ❌ you cannot do this
)}
</>
);
}You must use the Fragment element for this purpose:
import { Fragment } from 'react';
function ArticleList({ articles }) {
return (
<>
{articles.map((article) => (
<Fragment key={article.id}>{article.title}</> // ✅ you can do this
)}
</>
);
}Conclusion
Rendering lists in React is a foundational skill that enhances your ability to display dynamic data. By understanding the map() function, properly using keys, and following best practices, you can efficiently render lists and manage updates to the React application's UI.
No hints available.