Skip to content
Advertisement

How to make correct loop of JSON in React

I’ve got a problem with making a correct loop in React. I want to fetch data from JSON to don’t repeat components. I tried to make two loops and then two maps, but everything was in bad order. The other problem is that "description" is also an array that’s why I’m not able to deal with it

JSON:

{
  "oswiecim": [
    {
      "header": "Oświęcim Zasole",
      "description": [
        "Rejon ulic św Maksymiliana Kolbego",
        "i Stanisławy Leszczyńskiej"
      ]
    },
    {
      "header": "Oświęcim Zasole",
      "description": [
        "Rejon ulic Więźniów Oświęcimia",
        "Obozowej, Polnej i Legionów"
      ]
    },
    {
      "header": "Stare Miasto",
      "description": [
        "Rejon Rynku i Placu ks. Jana Skarbka oraz ",
        "ulic Zamkowej i Władysława Jagiełły"
      ]
    },
    {
      "header": "Stare Miasto",
      "description": [
        "Cmentarz Parafialny oraz rejon",
        "ul. Wysokie Brzegi."
      ]
    },
    {
      "header": "Osiedle Chemików",
      "description": [
        "Największa pod względem liczby ludności",
        "dzielnica Oświęcimia"
      ]
    }
  ]
}

React:

import '../../styles/selection/Selection.scss'
import { useEffect, useState } from 'react';

const Selection = () => {
    const [data, setData] = useState({})
    const getData = async () => {
        await fetch('https://jsoneditoronline.org/#left=cloud.b95a27020e1c45e9b3a7c95a74fc5d49', {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
            .then(res => res.json())
            .then(data => {
                setData(data)

            })
    }
    useEffect(() => {
        getData()
    }, [])

    const headers = []
    const descriptions = []
    for (const item of data.oswiecim) {
        headers.push(item.header)

        descriptions.push(item.description)

    }



    return (
            <div className="selection">
                    {headers.map(item => (
                        <h1>{item}</h1>
                    ))}
                  {descriptions.map(item => (
                    item.map(elem => (
                        <p>{elem}</p>
                    ))
                ))}
            </div>
    );
}

export default Selection;

The result should look like this:

example

Advertisement

Answer

You don’t need to separate header and description in two different variables.

So try something like this:-

return (
    <div className="selection">
      {data.oswiecim?.map((item) => (
        <>
          <h1>{item.header}</h1>
          {item.description?.map((description) => (
            <p>{description}</p>
          ))}
        </>
      ))}
    </div>
  );

Live demo

Advertisement