Here are some functional examples of rendering lists in React:
Using an `array of strings`:
const List = ({ names }) => {
return (
<ul>
{names.map(name => (
<li key={name}>{name}</li>
))}
</ul>
);
}
Using an `array of objects`:
const List = ({ users }) => {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Using a `for` loop:
const List = ({ names }) => {
return (
<ul>
{for (let i = 0; i < names.length; i++) {
<li key={i}>{names[i]}</li>
}}
</ul>
);
}
Using a `for...in` loop:
const List = ({ user }) => {
return (
<ul>
{for (let key in user) {
<li key={key}>{key}: {user[key]}</li>
}}
</ul>
);
}
Note: it is generally recommended to use the map() function to render lists in React, as it is more efficient and easier to read. The key prop is also important to include, as it helps React identify which items have changed, are added, or are removed.
(0)
Login first for like post.
Comments (0)