I am using React and trying to load data into my component from a local json file. I am trying to print all information, including the 'name' in a name:value pair (not just the value) to make it look like a form.
I am looking for the best way to do this. Do I need to parse? Do I need to use a map function? I am new to React so please show me solution with code. I've seen other questions similar to this but they include a lot of other code that I don't think I need.
Example of my code: test.json
{"person": {
"name": "John",
"lastname": "Doe",
"interests":
[
"hiking",
"skiing"
],
"age": 40
}}
test.js
import React, {Component} from 'react';
class Test extends Component {
render () {
return (
)
}
};
export default Test;
I need code that lets me import from json and code inside component that displays ALL fields.
To summarize, you can pass JSON data to other components using props or an event bus; which method to choose is for you to decide based on the requirements of your app. However, it is advised that you use props so that React can keep track of the data and communication between the components.
Create a local JSON file named data. json in the public directory of a blank Create React App project. Your React component's Fetch API requests always look for files or other relevant assets in this public directory.
If your json is stored locally, you don't have to use any library to get it. Just import it.
import React, {Component} from 'react';
import test from 'test.json';
class Test extends Component {
render () {
const elem = test.person;
return (
<ul>
{Object.keys(elem).map((v, i) => <li key={i}>{v} {test[v]}</li> )}
</ul>
)
}
};
export default Test;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With