0

I am having an issue to render my images from my './src/img' file and have no idea where i'm going wrong...

I have an object which have a key 'image' which return the file name (ie: 'filename.jpg'). As stated before, the images are stored in an 'img' folder in the 'src' one.

in my component, i return the image like this :

<div className='image'>
    <img src={require(`../img/${details.image}`)} alt={details.name} />
    {
        console.log(details.image)
    }
  </div>

i use the require function as i'm supposed to, (i think ?!^^) and indicates the folder and retrieve the image name with ${details.image}. As you can see i'm doing a console.log of details image which returns me the filenames without fail.

When i go into the console and check the rendering, i have no issue with the alt, but the src param gives me [object Module]

And that's where i'm kind of lost as to what happens and what i did wrong there.

Thanks by advance

2
  • 1
    require is not needed just add the path of the image in the string. And make sure you have img folder in the public path. Commented Dec 30, 2020 at 10:52
  • 1
    So i did as you said and it works fine. I tried to do a build just to check and no prob. Thank you very much ! (the render is now as follows : <img src={'../img/'+ details.image} alt={details.nom} /> Commented Dec 30, 2020 at 11:02

1 Answer 1

2

instead of the require module, try importing the image as suggested by creat-react-app docs.

import logo from './logo.jpeg';

import React from 'react';
import logo from './logo.png'; // <<<< image

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;   // <<<<<< Adding to src attribute.
}

export default Header;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, i used the previous answer though, but yours is more than logical enough. I'd may have to use states i guess but i could have thought of it before hand ^^

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.