Why is my path to my image not working in react?

Viewed 91

Here's my folder layout

src                                   (folder)
   images                             (folder)
         alligators                   (folder)
                  Alligator 1.svg     (svg file)
   main.js                            (javascript file)

And here's my line of code in main.js file:

    <img src={require("./images/alligators/Alligator 1.svg")} alt="alligator illustrator" />

I am getting no errors, I'm just getting my alt-text displayed and my image not being shown.

What seems to be my problem with my path?

I also just tried {} curly without "require", but the result is the same. I tried renaming Alligator 1 without a space, but again, the result is the same.

If my code is correct, what other possible reasons could this be happening?

2 Answers

Update your code to import the image and then use it in the src like this:

import alligator from './images/alligators/Alligator 1.svg';
...
<img src={alligator} alt="alligator illustrator" />

With the import your file gets stored into alligator and is then available for React to use. React then resolves it in your img tag.

in react.js, you can put your images inside of the public folder (the same directory as src), and then just serve it with it's default path, e.i :src="/image.svg"

Related