loading json data from local file into React JS
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
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
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?