i'm passing the following as props.
const people=['Eliana','Stefania','Ahmed']
{
people.map(function(name, index){
return <Person item={index} name={name}/>;
})
}
import Eliana from '../assets/imgs/people/eliana.png'
import Stefania from '../assets/imgs/people/stefania.png'
import Ahmed from '../assets/imgs/people/ahmed.png'
export default class Person extends React.Component {
render() {
return (
<div>
<img src={this.props.name} alt=''/>
<li key={this.props.item}>{this.props.name}</li>
</div>
);
}
}
what i'm doing here is using the above strings in the array to pass to a component and then generate images from that component by using the corresponding path, however when i pass the props, they display as strings, like Eliana would display as is in the img src?
how do i get corresponding paths? some kind of string conversion probably? i bet this is an easy one!
To display an image from a local path in React:Download the image and move it into your src directory. Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .
You could just use concatenate the entire URL besides the name, then concatenate the name
prop in it's place.
<img src={require('../assets/imgs/people/' + this.props.name + '.png')}
An easy fix for what you're asking about
<img src={require(this.props.name)} alt=''/>
But this is implying that you have the full path. What you currently have doesn't look like will work. In one way or another, each one has to end up with a path name, like this, when React interprets your code:
<img src={require('../assets/imgs/people/ahmed.png')} alt=''/>
A simple fix is to add the path as a string before your this.props.name
. It's standardized so all you have to do is add the name in, like so:
<img src={require(`../assets/imgs/people/${this.props.name.toLowerCase()}.png`)}/>
Be sure to document this though. You definitely want to document this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With