Lists
by Tomas TrescakΒ· React

Root Folder
Not Attempted
NameProgress
Introduction
Not Read
🍰 Player
Not Read
Setup
Not Attempted
NameProgress
Software Installation
Not Read
Project Setup
Not Read
Running and Testing
Not Read
React and ReactDOM
Not Read
πŸ’‘ Assignment 1: Welcome Message
Not Attempted
Submissions
Not Read
JSX and Components
Props
πŸ‘Ύ Exercise: Props
Not Attempted
CSS Styles
useState and Hooks
πŸ‘Ύ Exercise: useState
Not Attempted
Conditional Rendering
Lists
πŸ‘Ύ Exercise: Lists
Not Attempted
Forms and Events
πŸ‘Ύ Exercise: Forms
Not Attempted
πŸ’‘ Assignment 2: Front End
Not Attempted
Advanced React
Not Attempted
NameProgress
Pure Components - memo
Not Read
Lifecycle - useEffect
Not Read
Expensive? - useMemo
Not Read
DOM Interactions - useRef
Not Read
forwardRef
Not Read
useImperativeHandle
Not Read
πŸ‘Ύ useImperativeHandle
Not Attempted
Context
Not Read
useCallback
Not Read
useId
Not Read
useReducer
Not Read
Infrastructure
Not Attempted
NameProgress
Database
Not Read
NextAuth and Github Authentication
Not Read
Prisma and ORM
Not Read
Project Setup
Not Read
Project Authentication
Not Read
APIs
Not Attempted
NameProgress
APIs
Not Read
APIs - Slides
Not Attempted
Rest APIs
Not Read
Rest APIs - Express.js
Not Read
ReastAPIs - Next.js
Not Read
Securing APIs
Not Read
Securing APIs - NextAuth
Not Read
tRPC
Not Attempted
NameProgress
tRPC
Not Read
tRPC - Routers
Not Read
tRPC - Server Rendering
Not Read
tRPC - Client Rendering
Not Read
Persisting Data
Not Read
Assignment 3: APIs
Not Read
0 / 1070 XP

Lecture Transcript
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!

πŸ”‘ 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.

Maggie

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

Discussion

0 comments
Loading editor ...
Remember to be polite and report any undesirable behaviour

Category

Empty

Labels

Discussion has no labels

1 participant

user avatar

Priority

Notifications

You're not receiving notifications from this thread.
Course Outline