Reputation:
I have created react app using create-react-app , there is a component which need to be reused multiple times, this component contain <img>
tag, image is different for each instance of the component.
I am passing image path as imagePath prop from parent to child component and then that child need to load image from that path.
i can not use
import image from imagePath
because i don't know the path until component is build, and import statement don't work within component body.
I tried doing<img src={imagePath}>
that also don't work, can you point me to right direction?
adding code for further clarification
first approach it doesnt work. content is object passed by parent and content.image have value of ./images/keeper.PNG
import React from 'react';
import image from './images/keeper.PNG'
export default function Project(props)
{
return <div className='projectContainer' >
<div className='projectImage'>
<img src={props.content.image}
alt ='' />
</div>
<div className='.projectDescription'>
<h4>{props.content.name}</h4>
<p>{props.content.intro}</p>
<h5>Technologies and problems</h5>
<p>{props.content.tech}
</p>
</div>
</div> }
second methond <img src={image} alt ='' />
it works fine and show image but as stated above i don't know image path before the component is created
Upvotes: 3
Views: 1065
Reputation: 920
Try using it this way, where you can pass the imagePath via props
<img src={require(`${props.imagePath}`)} />
This alone will do the job.
When using Webpack you need to require images in order for Webpack to process them, which would explain why external images load while internal do not, so instead of img src= {"/imagePath"} you need to use img src= {require('/imagePath')} replacing imagePath with the correct image name for each of them. That way Webpack is able to process and replace the source img.
Upvotes: 0
Reputation: 9769
Sample
Parent component
let image = 'https://www.belightsoft.com/products/imagetricks/img/[email protected]'
function Parent(){
return <Child image={image}/>
}
Child component
function Child(props){
return <img src={props.image} alt="icon-image" />
}
or
directly if you import in component
import imagePath from './image.jpg';
function Child(props){
return <img src={imagePath} alt="icon-image" />
}
Upvotes: 1