Lists
by Tomas Trescak· React Fundamentals

0 / 3280 XP

Presentation Transcript
If you prefer text to video, check out the transcript of the presentation above

Slide 1 ----------- Part 1: 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. Slide 2 ----------- Part 1: 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. Part 2: In this example, we consider a simple list of numbers ... Part 3: ... and we will use the array's map function to iterate over array content and, for each array member, return a new LI element. Part 4: 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! Slide 3 ----------- Part 1: Keys are crucial in helping to determine which components have changed, added, or removed. This helps with efficient updates to the user interface. Part 2: 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. Part 3: 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! Slide 4 ----------- Part 1: A better practice for using keys is to use unique ids. Consider this example. Part 2: We have a list of todos, where each element has an id. Part 3: We can then use this id as a key in the list Part 4: When we render this component, everything behaves as expected. But make sure that key are truly unique. Part 5: If we would assign the same id to two todos ... Part 6: ... the warning about incorrect keys is back. Slide 5 ----------- Part 1: Let's check an example, where using array indices as key creates problems. Part 2: 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. Slide 6 ----------- Part 1: Let's discuss some best practices and common mistakes when dealing with lists. Part 2: 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. Part 3: Also, for performance reasons, keep components small and focused. Let a dedicated component render list items . Part 4: You should not use array indices as keys in arrays where the order or items can change. Part 5: You often forget to handle cases where the list might be empt or data might not be immediately available due to asynchronous loading. Slide 7 ----------- Part 1: Let's now take a look at a couple of common scenarios when rendering lists. Part 2: First, you can use the array's length property if you want to display a message when the list is empty. Slide 8 ----------- Part 1: Second, you may wish to render array elements without the root element. Part 2: But, you have to specify the key property and as a result you can not use the shorthand notation. Part 3: 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! 🔑 KEYS IN LISTS UNDERSTANDING KEYS Keys are a crucial concept when rendering lists in React [https://kentcdodds.com/blog/understanding-reacts-key-prop]. 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. [https://skillpies.s3.ap-southeast-2.amazonaws.com/courses/3myFj3C3s45Lw7am7p/sections/SqdHQny8jH31cMuH4b/Screenshot%202024-04-23%20at%2016.00.25.png] 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.
Maggie

Discuss with Maggie
Use the power of generative AI to interact with course content

Maggie is a generative AI that can help you understand the course content better. You can ask her questions about the lecture, and she will try to answer them. You can also see the questions asked by other students and her responses.

Discuss with Others
Ask questions, share your thoughts, and discuss with other learners

Join the discussion to ask questions, share your thoughts, and discuss with other learners
Setup
React Fundamentals
10 points
Next.js
10 points
Advanced React
Databases
10 points
React Hooks
Authentication and Authorisation
10 points
APIs
CI/CD and DevOps
Testing React
Advanced Topics