If you prefer text to video, check out the transcript of the presentation above
Rendering lists in React is a common task, as it allows developers to display dynamic data sets efficiently. This section will explore how to render lists, manage keys, and handle various data types.
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.
In this example, we consider a simple list of numbers ...
... and we will use the array's map function to iterate over array content and, for each array member, return a new LI element.
When we render this component, we see a correctly rendered list with all the numbers in the array. But we also see React's warning telling you that each child in a list should have a unique key prop. Let's fix that!
Keys are crucial in helping to determine which components have changed, added, or removed. This helps with efficient updates to the user interface.
The simplest way to fix this is to use the βindexβ parameter of the map function and assign it to the special "key" prop of the element. In React, every element or component has a key prop.
When we execute this code, the list renders as expected, and the error is gone! However, using an array index is not considered a good practice as it can bring issues when dynamically adding or removing new components, We will show you an example, when it can bring issues, but first let's discuss an alternative!
A better practice for using keys is to use unique ids. Consider this example.
We have a list of todos, where each element has an id.
We can then use this id as a key in the list
When we render this component, everything behaves as expected. But make sure that key are truly unique.
If we would assign the same id to two todos ...
... the warning about incorrect keys is back.
Let's check an example, where using array indices as key creates problems.
Here, we have two sets of controls. The first set uses dangerous indices in the form of array indices. The second set uses unique IDs. When we type some text in each set, we add a new element. The dangerous set incorrectly keeps the text in the first input, while the safe set correctly moves the input to a new line.
Let's discuss some best practices and common mistakes when dealing with lists.
First, you must always use unique keys when rendering lists. While this does not produce production errors, it may yield issues, as in the previous example.
Also, for performance reasons, keep components small and focused. Let a dedicated component render list items .
You should not use array indices as keys in arrays where the order or items can change.
You often forget to handle cases where the list might be empt or data might not be immediately available due to asynchronous loading.
Let's now take a look at a couple of common scenarios when rendering lists.
First, you can use the array's length property if you want to display a message when the list is empty.
Second, you may wish to render array elements without the root element.
But, you have to specify the key property and as a result you can not use the shorthand notation.
Consequently, you must import the Fragment element from react's library and use it as a parent of your array element. In 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.
Description
All the extra information about this section
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!
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) => <likey={todo.id}>{todo.text}</li>)}
</ul>
);
}
// Usage
const todos = [{id: 1, text: "Throw garbage"}, {id: 2, text: "Read book"}];
function App() {
return <ToDoListtodos={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.
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:
functionArticleList({ 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';
functionArticleList({ articles }) {
return (
<>
{articles.map((article) => (
<Fragmentkey={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.
Discuss with Maggie
Use the power of generative AI to interact with course content