Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs: How to import an image from a variable path

I am relatively new to Reactjs so I might be missing something obvious:

I have a component (DisplayFlags.js) that displays country flags along with country names depending on a previously chosen continent. I have everything set up: all possible flag images exist locally, I also have a js object called 'myCountries' that maps each continent to its countries, and each country to its name + local flag image name. Here is a part of it:

const myCountries ={
    "north-america": {
        "US": {
            "name": "United States",
            "picPath": "flag-of-United-States.png"
        },
        "UM": {
            "name": "United States Minor Outlying Islands",
            "picPath": "flag-of-United-States-Minor-Outlying-Islands.png"
        },
        "CA": {
            "name": "Canada",
            "picPath": "flag-of-Canada.png"
        },
        "MX": {
            "name": "Mexico",
            "picPath": "flag-of-Mexico.png"
        },
//etc
},
"south-america":{
  "AR": {
            "name": "Argentina",
            "picPath": "flag-of-Argentina.png"
        },
        "BO": {
            "name": "Bolivia",
            "picPath": "flag-of-Bolivia.png"
        },
//etc
}
}

What I am planning to do: loop through all the countries of a previously selected continent, and pass the "name" and "picPath" as props to another component, SingleCountry.js, who in turn displays them. My problem is with importing: I usually just write (example):

import randomImage from '../../img/icons/some-image-name.png'

And then use randomImage as the src of an img element in my component. In this case, is there a way to import an image from a path that is passed in props? Something like:

import flagImage from "../../img/flags/" + this.props.picPath

I understand that the above doesn't work because imports work outside of a component, and they don't have access to any kind of props. Can I import inside a component? Or should I totally drop this and import images in bulk in DisplayFlag.js then pass images one by one into SingleCountry.js?

like image 524
Ghadir Avatar asked Nov 14 '25 17:11

Ghadir


1 Answers

You could have a file import all the images like

//images/index.js

import image1 from './image1.png'
import image2 from './image2.png'
.
.
export default {
image1,
image2,
.
.
}

you can access images dynamically from the object exported from here

import images from './images/index.js'
images['image1'] 

// or dynamically
let name = 'image2'
images[name]
like image 141
Adithya Avatar answered Nov 17 '25 08:11

Adithya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!