Fahad Bilal Fahad Bilal - 5 months ago 38
Javascript Question

how to import images via props in react and use the 'import' path

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 (
<img src={this.props.name} alt=''/>
<li key={this.props.item}>{this.props.name}</li>

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!

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download