So earlier this week, I found out about an interesting way to map components in react. Here's an example of what I most commonly see.
A Todos component then returns a list of TodoCard:
export const Todos = () => {
return (
<div>
{todos.map(todo => (
<TodoCard key={todo.id} todo={todo} />
))}
</div>
)
}
Here we have to explicitly give react the key, or your console will be filled with a nasty error 🤮. Turns out we can let react handle the key with React.Children.toArray(). Lets refactor the above component:
export const Todos = () => {
return (
<div>
{React.Children.toArray(todos.map(todo => <TodoCard todo={todo} />))}
</div>
)
}
And tada 🎉, we no longer have to handle keys!
Top comments (0)