Populating data with React

Posted on

in

,

If the file is local (eg. the file config/updates.json below):

{
    "updates": [
        {
            "title": "Company A",
            "thumb": "company-a.jpg",
            "description": "blah",
            "tag": "React"
        },
        {
            "title": "Company B",
            "thumb": "company-b.jpg",
            "description": "blah",
            "tag":"jQuery"
        }
    ]
}

you can just import it:

import UpdatesFile from "../config/updates";
const updatesData = UpdatesFile.updates;

The constant ‘updatesData’ would give you a list of the data. You can put it as a prop in a component, map through it etc:

var updates = updatesData.map((update, i) =>
            (<>
               <h1>{update.title}</h1>
               <p>{update.description}</p>
             </>)
            );

If the data is external:

fetch('https://urlwherethedatais/')
      .then(resp => resp.json())
      .then(updatesData => this.setState({ updatesData:data.updates }));

where updatesData is a state. If you need it to work for older browsers like IE11 you’ll need polyfills for fetch and promise like isomestric-fetch and es-6-promise.

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