Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
51
rated 0 times [  55] [ 4]  / answers: 1 / hits: 32317  / 7 Years ago, tue, september 26, 2017, 12:00:00

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!


More From » reactjs

 Answers
26

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.


[#56386] Friday, September 22, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleyterryp

Total Points: 290
Total Questions: 92
Total Answers: 95

Location: Montenegro
Member since Sun, May 7, 2023
1 Year ago
;