Reputation: 25
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.
Upvotes: 2
Views: 3374
Reputation: 1482
In NextJS images are served from /
(root), so you shouldn't have to use public
in your path, or use require
for that matter. Just generate a standard string. It should be as simple as...
import aboutJson from './about.json'
const teams = aboutJson[teams]
const basePath = '/images/profiles/'
const Teams = () => (
<ul>
{teams.map((person) => <ProfileCard
key={person.id}
id={person.id}
name={person.name}
role={person.role}
major={person.major}
image={`${basePath}/${person.image}`}
/>
)}
</ul>
)
const ProfileCard = ({ image, ...props }) => <img src={image} />
Also, next does provide its own image component:
import Image from 'next/image'
const ProfileCard = ({ image, ...props }) => <Image src={image} />
Upvotes: 3