22

I need to import images(several) from my image file dynamically by a map method. First, I want to set a base URL to my images file and then read the image's name from my JSON file which includes the image property and then set the image src accordingly. The JSON file is like below :

{
      "title": "Blue Stripe Stoneware Plate",
      "brand": "Kiriko",
      "price": 40,
      "description": "Lorem ipsum dolor sit amet...",
      "image": "blue-stripe-stoneware-plate.jpg"
    },
    {
      "title": "Hand Painted Blue Flat Dish",
      "brand": "Kiriko",
      "price": 28,
      "description": "Lorem ipsum dolor sit amet...",
      "image": "hand-painted-blue-flat-dish.jpg"
    },

my images folder : enter image description here

I have read the products by redux which is works perfectly =>

const products = this.props.products;
console.log(products, 'from redux'); 
const fetchProducts = [];
    for (let key in products) {
      fetchProducts.push({
        ...products[key]
      });
    }

the console.log() => enter image description here

Now I want to define a base URL like this which later use as image src by adding the image's name from the JSON file in the map method :

const baseUrl = '../../components/assets/images/';
const fetchProducts = [];
for (let key in products) {
  fetchProducts.push({
    ...products[key]
  });
}

const productCategory = fetchProducts.map((product, index) => {
  return (
    <Photo
      key={index}
      title={product.title}
      brand={product.brand}
      description={product.description}
      imageSource={baseUrl + product.image}
      imageAlt={product.title}
    />
  );
});

my Photo component looks like below :

  const photo = props => (
  <div className={classes.Column}>
    <img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />
    <div className={classes.Container}>
      <p>{props.brand}</p>
      <p>{props.title}</p>
      <p>{props.price}</p>
    </div>
  </div>
);

export default photo;

unfortunately, I have faced this error: enter image description here Thanks in advance and sorry for my bad English :)

3
  • This import("../../components/assets/images/") Did you think this would somehow specify a folder for later use...? IF what you're trying to do is going to work at all, you have to combine the baseURL and image filename into a valid path first, then import it. Commented Sep 4, 2018 at 17:16
  • I had the same issue today, did you find a solution in the passed 2 years? :) Commented Nov 16, 2022 at 20:37
  • haha, Im not sure, if im remember correctly, the base URL solution worked Commented Nov 7, 2023 at 6:31

9 Answers 9

12

Import is not working like that. You can use a base URL like that:

const baseUrl = "../../components/assets/images/";

Then you can pass to your Photo component like that:

<Photo
  key={index} // Don't use index as a key! Find some unique value.
  title={product.title}
  brand={product.brand}
  description={product.description}
  imageSource={baseUrl + product.image}
  imageAlt={pro.title}
/>;

Lastly, in your Photo component use require:

<img src={require( `${ props.imageSource }` )} alt={props.imageAlt} />

or like that:

<img src={require( "" + props.src )} alt={props.imageAlt} />

But, don't skip "" part or don't use it directly like:

<img width="100" alt="foo" src={require( props.src )} />

since require wants an absolute path string and first two do this trick.

Sign up to request clarification or add additional context in comments.

7 Comments

thanks man, but I have faced another error : Uncaught Error: Cannot find module '/static/media/blue-stripe-stoneware-plate.8bf3a194.jpg,/static/media/hand-painted-blue-flat-
Can you update your question with your current code? It looks requiring is OK. Those names are dynamic and used by CRA (Webpack behind probably).l
Where is this file in your directory structure?
/src/components/assets/images
No, I mean this component's file place that you are using images in.
|
1

After trying all kinds of solutions, including backticks <img src={require( `${ props.imageSource }` )} and others, nothing was working. I kept getting the error Cannot find module, even though my relative paths were all correct. The only primitive solution I found, if you have a relatively small number of possible images, is to predefine a Map that will map to the actual imports. (Of course this won't work for lots of images.)

import laptopHouse from '../../images/icons/laptop-house.svg'
import contractSearch from '../../images/icons/file-contract-search.svg'
..

const [iconMap, setIconMap] = useState({
                                'laptopHouse': laptopHouse, 
                                'contractSearch': contractSearch, 
                                ..
                              });

..

<img src={iconMap[props.icon]} />

Comments

1

Try this solution for dynamic image:-

**Componet**
const photo = props => (
    <div className={classes.Column}>
      <img src={require( `../../components/assets/images/${props.imageSource}`)} alt={props.imageAlt} />
      <div className={classes.Container}>
        <p>{props.brand}</p>
        <p>{props.title}</p>
        <p>{props.price}</p>
     </div>
   </div>
);

**Include Componet**
const productCategory = fetchProducts.map((product, index) => {
    return (
      <Photo
        key={index}
        title={product.title}
        brand={product.brand}
        description={product.description}
        imageSource={product.image}
        imageAlt={product.title}
      />
    );
}); 

Comments

0

So here is what I found and it worked for me.

"file-loader": "4.3.0" React: 16.12

Run this in your terminal:

npm run eject

Check file-loader in config/webpack.config and located file-loader configurations. What I did was, I created a directory called static/media/{your_image_name.ext} following the notation there:

options: {
    name: "static/media/[name].[hash:8].[ext]"
}

and then imported this image like

import InstanceName from "static/media/my_logo.png";

Happy Hacking!

Comments

0

i solved this typescript issue as follows in my project. hope this is helpful

export const countryData = {
'sl': { name: 'Sri Lanka', flag: '/flag-of-Sri-Lanka.png' },
'uk': { name: 'UK', flag: '/flag-of-United-Kingdom.png' },
'usa': { name: 'USA', flag: '/flag-of-United-States-of-America.png' },
'ca': { name: 'Canada', flag: '/flag-of-Canada.png' },
'It': { name: 'Italy', flag: '/flag-of-Italy.png' },
'aus': { name: 'Australia', flag: '/flag-of-Australia.png' },
'me': { name: 'Middle East', flag: '/flag-of-Middle-East.png' },
'other': { name: 'Other', flag: '/flag-of-World.png' }, };

"part of URL within Double quotes" + dynamic_URL_via_var combo worked for me.

<Avatar src={require('../assets'+countryData['uk']['flag'])} />

Comments

0
  //json data.
  "ProductSlider":[
              {
                "image":"Product1.jpg"
              },
              {
                "image":"Product2.jpg"
              }]
   //mapping data list in parent component.
    {sliderData.map((data) => (
            <SwiperSlide className='w-10 '>
            <ProductCard data={{imgSrc: data.image}}  />
            </SwiperSlide>
          ))}
        
    //child component(linked image).
        import React from 'react'
        import { CardImg } from 'react-bootstrap'
        
        export default function ProductCard(props) {
          let {imgSrc} = props.data;
        
          return (
            <div className="overflow-hidden">  
              <div className='overflow-hidden bg-grey opacity-card' >
                <CardImg  
                      variant='top'
                      src={require(`../assets/images/${imgSrc}`)}
                     />
              </div>
              <div className='text-center p-1 opacity-card-title' >
                <div>Add to cart</div>
              </div>
            </div>
          )
        }

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

I was also facing the same problem in my React app. I tried to solve this problem & at last, I get a solution.

This thing works for me. I hope it will work for you as well.

I Place that image's folder where was my xyz.js file.

Before:- Not Working

/imgfolder
/workingfolder
    index.js

After:- Working

/workingfolder
    /imgfolder
    index.js file

I think it is not working if the images are outside the working folder, my assumption may be wrong but this thing works for me. Have a good day my friend.

Comments

0

if your images are in src file then try this

<img src={require("" + props.IMAGE_FULL_NAME_WITH_PATH_FROM_SRC)} alt={props.name} />

Comments

-2

Even I got the same error

{gallery.map((ch, index) => {....

cannot find module '/../..................png'

I went wrong here, I used src instead of ch

Error
<Image src={src.image} />
Solved
<Image src={ch.image} />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.