< Back to Coding, React

Using JSON in React

Sample JSON data:

{
    "Updates": [
        {
            "year": 2019,
            "updates": [
                {
                    "name": "A",
                    "type": "website"
                },
                {
                    "name": "B",
                    "type": "website"
                },
                {
                    "name": "C",
                    "type": "elearning"
                }
            ]
        },
        {
            "year": 2018,
            "updates": [
                {
                    "name": "2A",
                    "type": "website"
                },
                {
                    "name": "2B",
                    "type": "website"
                },
                {
                    "name": "2C",
                    "type": "elearning"
                }
            ]
        }
    ]
}

The data is sorted by year and each update has a name and type. To import this data into a component:

import UpdateData from "../config/updates";
const years = UpdateData.Updates;
const currentYear = years.find(update => update.year === 2019);

<YearsUpdates data={currentYear} />

Import the JSON by linking to it. Set a variable to contain all the data. We then want to pick out a certain year using “find”. Then we can use that variable as the component prop.

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *