0

I've built a React coded website but unfortunately I can't get the images to load correctly. I've referred to the documentation, and I'm trying to import them but I'm not sure how. It's throwing up an error when it's loading the website saying it can't resolve the images - which is another way of saying the file path isn't right?

For example - I'm trying to import from the 'Images' folder - so this would be the full file path:

src/Images/cycling.jpg

So I've tried importing the images as:

import './cycling.jpg';

import './Images/cycling.jpg

import cycling from './cycling.jpg';

import cycling from './Images/cycling.jpg';

I tried the second two because the documentation seemed to suggest you needed to define the image and name it - but if that's the case I don't know what the name I would need to use would be?

For reference too, I'm trying to import the images into the respective components file, which is located inside the same base src folder but under a separate Components folder.

src/Components/cycling.js

Probably worth noting too - other imports work perfectly and the website functions exactly as expected, except for the images.

Any help would be appreciated. Thanks!

Jon Nicholson
  • 927
  • 1
  • 8
  • 29
  • similar question with answer here: https://stackoverflow.com/questions/53014651/is-it-possible-to-serve-static-files-with-create-react-app-from-public-folder – Darren Jun 05 '20 at 15:10
  • how are you using the image, say `cycling`, in the component when you import? also, does it work locally and just fails when you deploy it somewhere - or doesn't work in your local environment either? – iamaatoh Jun 05 '20 at 15:18

1 Answers1

1

To serve static files in react, you will want to save those files inside the public folder. Public folder is automatically generated with create-react-app.

Save the images here: /react-app/public/Images/cycling.jpg

to use the image on your component: <img src="/Images/cycling.jpg" />

Official React Doc, Duplicate Question

Darren
  • 92
  • 10