Roger Staxx
Roger Staxx

Reputation: 439

Send data from array of objects to component

GOAL: Render 3 SearchItem components from locations[0].results[0] and 3 SearchItem components from locations[0].results[1]

I have an array of objects who's data I want to render in my SearchItem component:

const locations = [
    {
      results: [
        { name: "Rome, Italy", price: 100, distance: 1299, match: 96 },
        { name: "Beijing, China", price: 200, distance: 3000, match: 93 },
        { name: "California, USA", price: 250, distance: 420, match: 75 },
      ],
    },
    {
      results: [
        { name: "Rome, NY", price: 100, distance: 1299, match: 96 },
        { name: "Spain", price: 200, distance: 3000, match: 93 },
        { name: "California, USA", price: 250, distance: 420, match: 75 },
      ],
    },
  ];

And here is how I'm passing data via props to the component:

  {locations[0].results.map((location, index) => {
            return <SearchItem locations={locations[0].results[index]} />;
          })}

Now, when I console log in my SearchItem component only ```location[0].results[0] is printing.

Here is my SearchItem component:

function SearchItem({ locations }) {
  console.log(locations);
  return (
    <SearchItemsContainer>
     {location.name}
    </SearchItemsContainer>
  );
}

Any idea what I'm doing wrong?

Upvotes: 0

Views: 35

Answers (2)

crispengari
crispengari

Reputation: 9321

Try this:

{locations[0].results.map((location, index) => {
            return <SearchItem locations={location}  key={index} />;
})} 

Upvotes: 0

gandharv garg
gandharv garg

Reputation: 2171

Try the below code

{locations[0].results.map((location) => <SearchItem location={location} />)}
function SearchItem({ location }) {
  console.log(location);
  return (
    <SearchItemsContainer>
     {location.name}
    </SearchItemsContainer>
  );
}

Upvotes: 1

Related Questions