score:21
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?
score:0
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: 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>
);
}
}
score:1
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
score:4
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>
score:12
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))
score:13
- 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');
score:27
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
score:170
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
Source: stackoverflow.com
Related Query
- loading json data from local file into React JS
- Delay loading json data from local file into React JS
- Load Json data from local file into Typescript variable in REACT
- How can I get data from a local file into my React app?
- read JSON file from local hard drive and parse into react app
- React Hook useEffect to fetch data from local json file to create a details page
- Fetch data from JSON local file in React
- Writing data from form to local JSON file with React
- Dynamically Load Project Data from JSON file into React
- Retrieving data from a local json file in react
- Unable to fetch data from local json file by axios
- React - load all data from json into component
- How to get data from local json file using actions and axios.get() (Redux)?
- Loading JSON file into React Component state | Wepback2
- Reading data from JSON file using react
- How to fetch and display data from json file in react typscript
- React - how to populate one select menu based on a value of another select menu using data from a local .json file
- Loading local JSON file in React for dynamic content
- D3.csv not loading data from local csv file
- Fetching data from local json file
- Load any kind of data from a local file in a React app
- Inserting JSON File Data into React Bootstrap Table 2
- How can I filter json data from api call in react into different sections of the component
- Local json file is not loading using ajax in react js
- Accessing data from local file by id (from params, React Router v6)
- Could not fetch local JSON file from public folder in React
- While accessing data from a [ JSON file ] it shows undefined In react js
- I have been trying to use Fetch to get data from an external json file with react but kept getting errors
- ReactJS - Error while loading data from json file
- Fetching data from local JSON file using axios and displaying data
More Query from same tag
- one of my controllers is not rendering when I update the store
- Dynamically Define ReactJS Routes from JSON
- React hooks vs eventListener
- JavaScript React async/await returning the wrong body?
- Migrating to Styled-Components with global SASS variables in React
- Passing methods between components in reactJS
- How to use graphql-request's batching via the batchRequests() function in redux-saga?
- How to remove only one instance using Array.prototype.filter()
- The "file" argument must be of type string. Received type undefined on npm run deploy to gh-pages
- Select the data from input
- Running a React functional component with redux store.subscribe
- Lodash: filter then map over an object
- ReactJS rendering image from array
- How do you make react-tsparticles scrollable in a website? When I scroll down, I want it to go up and not sticky
- PurgeCSS removing Tailwind font in next.js
- componentWillReceiveProps, componentDidUpdate for React Hook
- React continuously rendering when calling useEffect dependency
- Passing characters to a components ignores spaces in React Js
- How to fix the Rendered more hooks than during the previous render using react hook
- Redux props are being received in Redux DevTools but not in the React component
- browserify - exclude code blocks?
- How to pass an external method to a stateless functional component in React
- Sort By Last Name Data fetched from API In React JS
- How to access value of a routing parameter in react?
- How to Create an AutoComplete in React
- override component mui v5 react
- I am trying to filter out data but not able to display them properly
- Immutability-Helper Updating One Property but not Others?
- Open Modal on page load causing Maximum update depth exceeded
- How to get a reference to target element inside a callback