loading json data from local file into React JS
Solution 1
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?
Solution 2
I was trying to do the same thing and this is what worked for me (ES6/ES2015):
import myData from './data.json';
I got the solution from this answer on a react-native thread asking the same thing: https://stackoverflow.com/a/37781882/176002
Solution 3
The simplest and most effective way to make a file available to your component is this:
var data = require('json!./data.json');
Note the json!
before the path
Solution 4
- Install
json-loader
:
npm i json-loader --save
- Create
data
folder insrc
:
mkdir data
Put your file(s) there.
Load your file:
var data = require('json!../data/yourfile.json');
Solution 5
If you have couple of json files:
import data from 'sample.json';
If you were to dynamically load one of the many json file, you might have to use a fetch
instead:
fetch(`${fileName}.json`)
.then(response => response.json())
.then(data => console.log(data))
Desmond
Updated on July 08, 2022Comments
-
Desmond almost 2 years
I have a React component and I want to load in my JSON data from a file. The console log currently doesn't work, even though I'm creating the variable data as a global
'use strict'; var React = require('react/addons'); // load in JSON data from file var data; var oReq = new XMLHttpRequest(); oReq.onload = reqListener; oReq.open("get", "data.json", true); oReq.send(); function reqListener(e) { data = JSON.parse(this.responseText); } console.log(data); var List = React.createClass({ getInitialState: function() { return {data: this.props.data}; }, render: function() { var listItems = this.state.data.map(function(item) { var eachItem = item.works.work; var photo = eachItem.map(function(url) { return ( <td>{url.urls}</td> ) }); }); return <ul>{listItems}</ul> } }); var redBubble = React.createClass({ render: function() { return ( <div> <List data={data}/> </div> ); } }); module.exports = redBubble;
Ideally, I would prefer to do it something like this, but it's not working - it tries to add ".js" onto the end of the filename.
var data = require('./data.json');
Any advice on the best way, preferably the "React" way, would be much appreciated!
-
Desmond almost 9 yearsThanks very much for your help John. I've been looking into how to update the component on the callback but not having much luck. Is it to do with the state? I'm still a newbie to React! I've updated the code to show how the component is working - are you able to tell me how to pass the data in on callback? Thanks again!
-
John Weisz almost 9 years@Desmond Yes, state can work, as a component will be rerendered when its state changes.
-
kevr over 7 yearsIf you're using this method with webpack, you need json-loader for the imported json files.
-
Gopinath Langote almost 7 yearsThis will not work unless you add a library for that. As this is not supported by default in React. example library :- npmjs.com/package/json-loader
-
Matt Brand almost 7 yearsThank you! I've been looking for a simple way to access json data in JSX, and this is exactly it!
-
agm1984 over 6 years
json-loader
is included with newer Webpack versions, I believe, but you may still need to add something to your Webpack config to use that exact syntax. Do some research into it. -
cdvel over 6 years@agm1984 things have changed since 2015, it would be nice if you provide a complete answer instead.
-
agm1984 over 6 yearsI believe the newest Webpack versions include json-loader so you do not need to install it or declare it in your config file. I would recommend trying to just
import FILE_AS_VARIABLE from './file/location.json'
-
agm1984 over 6 yearsSee answer here: stackoverflow.com/questions/43735486/…
-
agm1984 over 6 yearsAlso see the answer in this question by
rockfakie
-
Wilson Biggs over 5 yearsNote that this will compile your JSON into the bundle, making hot-swapping JSON files impossible. That's probably fine for a lot of use cases, but it wasn't for mine.
-
ssc over 5 years
zero-latency quantum-entanglement connection
😂 maybe it's time to invent those, just so that people don't have to learn about async anymore... -
Syed Aqeel about 5 yearsthis answer should be marked as the most accurate answer, but with
json-loader
package example -
Max MacLeod over 4 yearswith React v16.11.0 and a default project init, was able to simply add
var data = require('./data.json');
-
secavfr over 4 yearsA had the "Critical dependency: the request of a dependency is an expression" error when NOT using
json!
. Thanks. -
Chamod Pathirana over 4 yearsis there anyway that I can use .json file from outside of the src folder? I am using create-react-app for my project
-
Max MacLeod over 4 yearsWorked for me. I’m using rollup. Previously had
var data = import(‘./data.json’)
which imported a Promise. Changing this toimport data from ‘./data.json’
gave direct access to the imported object. -
lharby over 3 yearsAdding code is great but you need to explain your code with comments.
-
Khadim H. over 2 yearsyes! but I explain in short way. Next time I will try to add code with explanation. thank you