loading json data from local file into React JS

JavascriptAjaxJsonXmlhttprequestReactjs

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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 2 - Javascript

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 3 - Javascript

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 4 - Javascript

  1. Install json-loader:
npm i json-loader --save
  1. Create data folder in src:
mkdir data
  1. Put your file(s) there.

  2. Load your file:

var data = require('json!../data/yourfile.json');

Solution 5 - Javascript

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))

Solution 6 - Javascript

My JSON file name: terrifcalculatordata.json

[    {      "id": 1,      "name": "Vigo",      "picture": "./static/images/vigo.png",      "charges": "PKR 100 per excess km"    },    {      "id": 2,      "name": "Mercedes",      "picture": "./static/images/Marcedes.jpg",      "charges": "PKR 200 per excess km"    },    {        "id": 3,        "name": "Lexus",        "picture": "./static/images/Lexus.jpg",        "charges": "PKR 150 per excess km"      }]

First , import on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

then after return:

  <div>
  {
    calculatorData.map((calculatedata, index) => {
        return (
            <div key={index}>
                <img
                    src={calculatedata.picture}
                    class="d-block"
                    height="170"
                />
                <p>
                    {calculatedata.charges}
                </p>
            </div>
                  

Solution 7 - Javascript

You could add your JSON file as an external using webpack config. Then you can load up that json in any of your react modules.

Take a look at this answer

Solution 8 - Javascript

If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.

Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: https://stackoverflow.com/questions/3582671/how-to-open-a-local-disk-file-with-javascript

I will include a slightly modified version for using it in React:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
    this.handleFileSelect = this.handleFileSelect.bind(this);
  }

  displayData(content) {
    this.setState({data: content});
  }

  handleFileSelect(evt) {
    let files = evt.target.files;
    if (!files.length) {
      alert('No file select');
      return;
    }
    let file = files[0];
    let that = this;
    let reader = new FileReader();
    reader.onload = function(e) {
      that.displayData(e.target.result);
    };
    reader.readAsText(file);
  }

  render() {
    const data = this.state.data;
    return (
      <div>
        <input type="file" onChange={this.handleFileSelect}/>
        { data && <p> {data} </p> }
      </div>
    );
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDesmondView Question on Stackoverflow
Solution 1 - JavascriptrockfakieView Answer on Stackoverflow
Solution 2 - JavascriptcdvelView Answer on Stackoverflow
Solution 3 - JavascriptJohn WeiszView Answer on Stackoverflow
Solution 4 - JavascriptChaosPredictorView Answer on Stackoverflow
Solution 5 - JavascriptjsbishtView Answer on Stackoverflow
Solution 6 - JavascriptKhadim H.View Answer on Stackoverflow
Solution 7 - JavascriptRishab DoshiView Answer on Stackoverflow
Solution 8 - JavascriptbiziView Answer on Stackoverflow