Using JSON in React

Posted on

in

,

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.

Leave a Reply

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

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930