Typing Lists and Keys
Glissez pour afficher le menu
In React, lists are used to render multiple items. In TypeScript, you define the type of items inside the list, so each item has a clear structure.
Typing a List of Values
const items: string[] = ["Apple", "Banana", "Orange"];
Rendering a list:
items.map((item) => <li key={item}>{item}</li>);
- Each item is a string;
- Key helps React track elements.
Typing a List of Objects
type User = {
id: number;
name: string;
};
const users: User[] = [
{ id: 1, name: "Alex" },
{ id: 2, name: "John" },
];
Rendering object list:
users.map((user) => (
<li key={user.id}>{user.name}</li>
));
- Each item follows the
Usertype; - Use a unique key (like
id).
Define the type of list items, and use a unique key when rendering them.
Tout était clair ?
Merci pour vos commentaires !
Section 1. Chapitre 28
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion
Section 1. Chapitre 28