My goal is to use data from a json file to pass certain information using the concept of props in react in order to load multiple images (cards).
I am using three components to complete this project, App, MainCard, and the json file called Data.
I am having difficulty getting the image to load.
here is the json file
{
"HipHop": [
{
"id": 1,
"url":"../public/MainCardImages/hiphopMainCard.png",
"description": "HipHopCard",
"title": "Hip Hop"
}
],
"House":[
{
"id": 2,
"url":"../public/MainCardImages/houseMainCard.png",
"description": "House Card",
"title": "House"
}
]
}
here is app.jsx
import MainCard from './components/MainCard'
import Data from "./data.json"
function App() {
const maincard = Data.map(card => {
return(
<MainCard image={card.HipHop.url}/>
)
})
return (
<div className="App">
{maincard}
</div>
) }
and here is MainCard
function MainCard(props){
return(
<div className="mainCard">
<img src={props.image} />
</div>
)
}
CodePudding user response:
Instead of keeping the data in a json file, I would instead use a js file like this.
export default data = [
{
id:1,
url:process.env.PUBLIC_URL "/MainCardImages.hiphopMainCard.png",
description:"HipHopCard",
title:"Hip Hop"
},
{
id:2,
url:process.env.PUBLIC_URL "/MainCardImages.houseMainCard.png",
description:"House Card",
title:"House"
}
]
Also I used process.env.PUBLIC_URL
instead of ../public
because in my projects I always get some sort of error if I do it that way.
CodePudding user response:
If you have a component with a prop called image
:
<MainCard image={card.HipHop[0].url}/>
Inside that component, you should reference it as image
:
function MainCard(props){
return(
<div className="mainCard">
<img src={props.image} />
</div>
)
}
As @James points out, you would have to reference your url like card.HipHop[0].url
because HipHop
is an array.
CodePudding user response:
As you can see by your outer-most curved brackets, you are currently trying to use the map function to iterate through an object, when it needs to be an array:
const newArray = Object.values(Data);
Only use this if you do not have control over the JSON's initial shape!
If you do, however, just make sure it's an array from the get-go (square brackets on the outside).