I'm trying to dynamically load information from this JSON file and plug it into a component.
{
"team": [
{
"id": "",
"name": "",
"role": "",
"bio": "",
"major": "",
"image": "akh.jpg"
},
{
"id": "",
"name": "",
"role": "",
"bio": "",
"major": "",
"image": "chr.jpg"
}
]
}
The location of my code is /pages/about/index.js
and my JSON file is in /pages/about/about.json
.
They way I'm parsing the code is like this:
var data = require('./about.json')
var teams = data['team'];
<ul>
{teams.map((person) => {
var basePath = "/public/images/profiles/";
var loc = require(basePath + person.image);
return <ProfileCard key={person.id} id={person.id} name={person.name} role={person.role} major={person.major} image={loc} />
})}
</ul>
The component is located in the same file. I'm only attaching the img element from the profile since the rest work fine.
<img className="" src={require(props.image)}></img>
If I take out the img element or put in an actual path, it works perfectly but this way isn't working. The only similar post I could find was this one, but it never got an answer. StackOverflow: importing image dynamically (React Js) (Require img path cannot find module)
Updated Code 1:
<ul>
{teams.map((person) => {
var basePath = "/public/images/profiles/";
return <ProfileCard
key={person.id}
id={person.id}
name={person.name} r
role={person.role}
major={person.major}
image={`${basePath}/${person.image}`} />
})}
</ul>
And the component is now like this after removing require()
.
<img src={props.image}></img>
Updated Code 2:
Switched to next/image
from img and it works! I had to remove the last /
and it worked.