Import JSON File in React

Import JSON file in React

One nice way (without adding a fake .js extension which is for code not for data and configs) is to use json-loader module. If you have used create-react-app to scaffold your project, the module is already included, you just need to import your json:

import Profile from './components/profile';

This answer explains more.

how to import json data file and use it in a react component?

You can not directly import your json array from the JSON file in react. To achieve that you must store your JSON array in a variable and then export default your JSON array. By Doing this you can easily import it in your component.

FakeData.js

const fakeData = [
{
"id": 1,
"avartar": "url/128.jpg",
blah blah blah...
},
]

export default fakeData // you must export it to use in another file.

Then in any component use it like

import fakeData from './Destination_of_file/fakeData.js' 

or

Way 2 // recomended
import fakeData from './Destination_of_file/fakeData'

Import static JSON data in React

There are 2 workarounds for loading json files in a js file.

  1. Rename your json file to .js extension and export default your json from there.

  2. Since json-loader is loaded by default on webpack >= v2.0.0 there's no need to change your webpack configs.

    But you need to load your json file as json!./data/jsonResponse.json (pay attention to json!)

EDIT:

Cannot read property 'props' of undefined

The reason you're getting this error is because you're trying to access this on a functional component!

loading json data from local file into React JS

You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListener callback function will not execute synchronously with your code (that is, before React.createClass), but only after your entire snippet has run, and the response has been received from your remote location.

Unless you are on a zero-latency quantum-entanglement connection, this is well after all your statements have run. For example, to log the received data, you would:

function reqListener(e) {
data = JSON.parse(this.responseText);
console.log(data);
}

I'm not seeing the use of data in the React component, so I can only suggest this theoretically: why not update your component in the callback?

How to fetch data from local JSON file on react native?

Since React Native 0.4.3 you can read your local JSON file like this:

const customData = require('./customData.json');

and then access customData like a normal JS object.



Related Topics



Leave a reply



Submit