Home > Mobile >  How to iterate and extract single objects from an array of objects to render in React
How to iterate and extract single objects from an array of objects to render in React

Time:11-24

I'm getting some data from an API that's coming as an array of objects and want to extract them and destructure them so I can use them to render a component in React. I have achieved something somewaht but this way I'm not KISS and also to render it is creating the item 6 times for each one of them so I have 24divs.

Data is coming like this, "hourly" array with 48 objects. I already slice the array to only use six as that all I need.

"hourly": [
{
  "dt": 1618315200,
  "temp": 282.58,
  "feels_like": 280.4,
  "pressure": 1019,
  "humidity": 68,
  "dew_point": 276.98,
  "uvi": 1.4,
  "clouds": 19,
  "visibility": 306,
  "wind_speed": 4.12,
  "wind_deg": 296,
  "wind_gust": 7.33,
  "weather": [
    {
      "id": 801,
      "main": "Clouds",
      "description": "few clouds",
      "icon": "02d"
    }
  ],
  "pop": 0
},
...

This is what I got inside my return and within section tags which does work but I don't think is the best way to do it, also it's a nightmare to style it properly as it creates six items each time:

<div className="weather-info-extra">
    {shortedArr.map((i, index) => (
      <div key={index}>
        {new Date(i.dt * 1000).toLocaleTimeString([], {
          timeZone: timezone,
          hour: '2-digit',
          minute: '2-digit',
          hour12: true,
        })}
      </div>
    ))}
    {shortedArr.map((i, index) => (
      <div key={index}>{i.weather.map(w => w.description)}</div>
    ))}
    {shortedArr.map((i, index) => (
      <div key={index}>{i.temp} C</div>
    ))}
    {shortedArr.map((i, index) => (
      <div key={index}>
        <p>Rain</p>
        {i.pop}%
      </div>
    ))}
  </div>

I know there's a very obvious way that I'm missing to get each object from the array so I could render it better.

CodePudding user response:

You’re right that you can do this more efficiently. You only need to map once. You can use a fragment to encase the multiple elements, this fragment is never rendered but allows you to have multiple children.

shortArray.map((data, index) => (
    <React.Fragment key={index}>
        <div>{data.time}</div>
        <div>{data.weather}</div>
        // anything else you want rendered
    <React.Fragment />
));

There’s no need for you to map this array multiple times.

Just a side note, fragments that don't need keys can be written as empty tags in JSX:

<> /** React fragment code here */ </>

  • Related