Home > front end >  can't specify image path inside js file
can't specify image path inside js file

Time:03-06

I am trying to import image from 'images' folder inside 'home.js' file which is inside components folder. I tried many combinations of '../' and './', but image doesn't load on page. There is probably something wrong with a path.

my directory looks like this

tree screenshoot

CodePudding user response:

The correct syntax in react is:

import astronaut from '../images/astronaut.png';

<img src={astronaut} alt="logo" />

CodePudding user response:

Since you are using React, did you check if the component is even being rendered to the view at all? Additional factor could be your applied classes 'home-wrapper' or 'backImg'

I usually add some placeholder text to check if it pops up.

Regarding to Omars answer, that's right you would only need to go back two directories to access that image, like so

<img src="../../images/astronaut.png" alt="astronaut"/>

CodePudding user response:

When you provide a relative URL, it has to go from the URL of the HTML to the URL of the image.

You are trying to go from the file path of the JavaScript file to the file path of the image.

Since the image is not in the public directory, it is quite likely that the image doesn't even have a URL in the first place.


There are two basic approaches you can use to determine the URL here.

Manually

You need to put the image somewhere it has a URL.

How you do this will depend on the HTTP server you are using. You will need to ensure that the image has the same URL (or at least one relative to the HTML document) in both your development and production environments.

For example, you could put it in the public directory, then say src="public/images/yourimage.jpeg". (Note that I'm making assumptions about how your development server allocates URLs to files in the public directory here).

Use your bundler

Typically when using React (as you appear to be doing) you will use a tool like Webpack to generate a production ready version of the site. This will do things like removing slow debugging routines, tree shaking to remove code from modules that isn't being used, and so on.

Webpack has features for handling images so once you set up the configuration file to support it, you can then do:

import MyImage from '../../../images/yourimage.jpeg';

and

<img src={MyImage} alt="etc etc" />

Note that the path here is relative to the JS file and that you need to use {} to assign a variable's value to src.

  • Related