< Back to Coding, React

Populating data with React

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.