0

I am working on a React Table. How can I fetch data from an external json file and display the data from that json file?

Here is my CodeSandbox - https://codesandbox.io/s/jl8zznpzyv

I have added a json file. Being a beginner in React, I am not aware about how to fetch data from an external json file and display the data from that json file.

1 Answer 1

3

Export your JSON file through a variable (using let, const), and import it into your file where you need that JSON data.

have a look:-

sample.js

const sampleData = [
   {
     "firstName": "Sam",
     "lastName": "Jones",
     "age": "a"
   },
  {
     "firstName": "Sam1",
     "lastName": "Jones1",
     "age": "a"
   },
]

export default sampleData;

and now importing it in my file where i want to use my data

home.js

import React, { Component } from 'react'
import sampleData from './sample.json'

export default class Home extends Component{
    render(){
         return(
              <div>
                { sampleData.map((item, i) => {
                   return (
                        <div>
                          <h4> My Name is {item.firstName} {item.lastName} and my age is {item.age}.</h4>
                        </div>
                   )
                 }
              </div>
          )
     }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Can I assign that constant to a state variable?
i don't understand what you mean to say
I meant if I have the json in a different file and I am trying to use its values in a different file then can I assign that constant to a state variable? Can you kindly show me in my CodeSandbox?
I cannot see any change. Probably you haven't saved after forking. Also I want to remove the data: makeData() method and get data from the json file
Can you click on fork, then do the change and the save. It will generate a new url.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.