Mapping React Components

We can use the JavaScript map function to make our code a lot cleaner when creating multiple components of the same type from a JSON-type data source.

So instead of having something like this:

function App() {
   return (
      <div>
         <Card 
            name={contacts[0].name}
            img={contacts[0].img}
            tel={contacts[0].phone}
          />
          <Card 
            name={contacts[1].name}
            img={contacts[1].img}
            tel={contacts[1].phone}
           />
          <Card 
            name={contacts[2].name}
            img={contacts[2].img}
            tel={contacts[2].phone}
           />
         ...

We can use something like this:

function createCard(contact) {
   return <Card name={contact.name} img={contact.img} />
}

function App() {
   return (
      <div>
         {contacts.map(createCard)}
         ...

We still have something to fix though. Once you run your new code, you should get this warning:

This is because we don’t have a key prop in our child components. The key must be unique among each of the mapped components.

function createCard(contact) {
   return <Card 
      key={contact.id}
      name={contact.name} 
      img={contact.img} 
   />
}

The key CANNOT be used as a property in the component’s props array. The key is for React to use, not us.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s