DEV Community

loading...

An better way to map over components in React

rushi444 profile image Rushi Arumalla ・1 min read

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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>
  )
}
Enter fullscreen mode Exit fullscreen mode

And tada 🎉, we no longer have to handle keys!

Discussion (0)

pic
Editor guide