Reputation: 425
I am trying to import and iterate data from .json file.
For that, I am importing .json file and using the map function to iterate over data as shown in App.js file
App.js
import React from 'react';
import characters from "./data/characters.json"
import './App.css';
function App() {
return (
<div className="App">
<ul>
{
characters.map(character => {
return <li key={character.name}>{character.name}</li>
})
}
</ul>
</div>
);
}
export default App;
characters.json
{
"characters": [
{
"name": "Luke Skywalker",
"url": "https://swapi.co/api/people/1/"
},
{
"name": "C-3PO",
"url": "https://swapi.co/api/people/2/"
},
{
"name": "Leia Organa",
"url": "https://swapi.co/api/people/unknown/"
},
{
"name": "R2-D2",
"url": "https://swapi.co/api/people/3/"
}
]
}
But I am getting an error ".map is not a function". Could anyone tell me how should I correct my error?
Upvotes: 1
Views: 97
Reputation: 17608
Because you are importing your file as characters
name and that file includes an object and that object includes a characters
property. So it should be like that:
function App() {
return (
<div className="App">
<ul>
{
characters.characters.map(character => {
return <li key={character.name}>{character.name}</li>
})
}
</ul>
</div>
);
}
You can import the file as another name to prevent name confusion maybe.
import charactersFile from "./data/characters.json"
...
charactersFile.characters.map(character => {
Upvotes: 3