Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 509
Fahad Bilal Avatar asked Sep 26 '17 03:09

Fahad Bilal


People also ask

How do I give an image a path in React?

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" /> .


2 Answers

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')}
like image 31
Gage Hendy Ya Boy Avatar answered Oct 19 '22 02:10

Gage Hendy Ya Boy


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.

like image 115
Andrew Avatar answered Oct 19 '22 01:10

Andrew