Conteúdo do curso
Immersion in React: Comprehensive Course for Beginners
Sobre a Aula

Rendering Data Lists

In the previous topic, we learned about using ternary operators for conditional rendering. Today, let’s learn about rendering data lists in React.

What are Data Lists?

Data lists are collections of information organized in a linear structure. In React, we can render data lists using various methods, such as:

  • Map components: The map component is a functional component that allows iterating over a data list and rendering an element for each item in the list.
  • For loops: We can use for loops to iterate over a data list and render elements conditionally.
  • Custom components: We can create custom components to render data lists in a more complex and reusable way.

Example of Rendering Data Lists

Let’s see an example of how to render a data list using the map component:

const products = [
  {
    id: 1,
    name: "Product 1",
    price: 10.00,
  },
  {
    id: 2,
    name: "Product 2",
    price: 20.00,
  },
  {
    id: 3,
    name: "Product 3",
    price: 30.00,
  },
];

const App = () => {
  return (
    <div>
      <h1>Product List</h1>
      <ul>
        {products.map((product) => (
          <li key={product.id}>
            {product.name} - ${product.price}
          </li>
        ))}
      </ul>
    </div>
  );
};

In this example, the App component renders a list of products using the map component. The map component iterates over the products list and renders an li for each product. The li contains the name and price of the product.

Important Notes

When rendering data lists, it’s important to:

  • Use keys: Each item in the list should have a unique key. The key is used to identify the item in the list and to optimize rendering.
  • Avoid mutations: It’s important to avoid mutating the data list directly in the component. If you need to modify the data list, make a copy of the list and modify the copy.

Summary

  • Render lists with map, for, or custom components.
  • Use keys to identify each item in the list.
  • Avoid mutating the list directly in the component.
Entrar na conversa
Rolar para cima