skip to Main Content

I am having a heck of a time trying to load dynamic images while mapping in the return statement. If the image is static, no probablems.

This works:

src={require('../../assets/user-images/image-anne.jpg')}

However, I am mapping through a list of comments and need to display the images dynamically from the path given in the image path of the props.

The image prop looks like:

‘./assets/user-image/image-anne.jpg’

So I tried the following but this does not work:



src={require(`../.${image}`)}


I get the following:



“Cannot find module ‘./../assets/user-images/image-anne.jpg”



I also try just using {image} but it doesn’t seem to know to look for the assets folder under src.



I am trying to load the images in a component under src/components/feedbackList



The images are in src/assets/user-images

If I go directly for the assets folder is gives me the standard "/assets falls outside of the /src directory."

Any direction is appreciated.

2

Answers


  1. Here is an example code for dynamically changing img src

    const [imageSrc, setImageSrc] = useState('');
    
    const loadImage = () => {
      // Update the image source dynamically
      setImageSrc('path/to/your/image.jpg');
    };
      // Pass the state to img src
    <img src={imageSrc} alt='image'/>
    
    Login or Signup to reply.
  2. Follow this tips to able to load image.

    1. See the Path is correct or not using import.
    2. Console.log of path and Check it.
    let propUrl = "./assets/user-image/image-anne.jpg";
    
    let url = "../."+ propUrl;
    
    console.log(url)
    1. If not working above the tips then use this one.

      src={require("../." + image).default}

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search