Answer the question
In order to leave comments, you need to log in
How to render JSON in React.js?
There is a JSON file:
{
"books": {
"book1": {
"id": 1,
"name": "Sample",
"author": "Somebody",
"genre": "Tales"
},
"book2": {
"id": 2,
"name": "Winter",
"author": "Ted"
}
}
}
import data from './books.json';
class Home extends Component {
render(){
const carNode = () => {
return (
<tr>
<th scope="row">{data.books.book1.id}</th>
<td>
<p>
<Link
to={"books/"+data.books.book1.id}
key={data.books.book1.id}>
{data.books.book1.name}
</Link>
</p>
<p className="author">{data.books.book1.author} </p>
</td>
</tr>
)
};
return (
<div className="container-fluid content-main">
<div className="row">
<div className="col-xl-12">
.........
<p>{carNode()}</p>
.........
</div>
</div>
</div>
);
}
}
Answer the question
In order to leave comments, you need to log in
Whenever you get a structure, you need to iterate through it all the way through each element to generate a JSX element. For arrays, they usually use the .map method, for objects, for example , Object.keys (of course, the forEach loop for an array, and the for in loop for an object, etc.) are also suitable.
Since you don’t get an array of objects in JSON, and an object of objects, then you need to run through Object.keys, for example, and then apply a map to the resulting array of keys. An example of the resulting array:
Apply map:
In this case, the template variable will contain 2 JSX elements (span tags with data). You probably want it to be tr. It’s not difficult to change)
And you need a json-loader so that webpack can correctly import such files, since while there is no json-loader, webpack does not know how to process files with the .json extension. By the same principle, you include css-loader, for example, so that webpack can "import css"
I want to add json data structure. If possible, store data in the format of an array of something, not an object of something. The map method for an array is faster than the same for in for an object.
{
books: [ { id: 1, name: "Sample", author: "Somebody", genre: "Tales" }, { id: 2, name: "Sample2", author: "Somebody2", genre: "Tales2" } ]
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question