V
V
Vlad2021-03-29 22:07:40
React
Vlad, 2021-03-29 22:07:40

Image path in React.js?

It seems like the path to the src attribute should be based on the file architecture.
In order not to depend on the route, I'm trying to get to the image through an absolute link.
As a result, at ` localhost:3000/components/Users/img/johnson.jpg ` I get 404.
Why does this happen in React?

let { userName } = useParams();
/* ... */
<img src={`${window.location.origin}/components/Users/img/${userName}.jpg`} />

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan V, 2021-03-29
@Vextor-ltd

If the picture is in " /components/Users/img/johnson.jpg " and you want to set the path to it in the Users component, then write like this

import johnsonImg from "./img/johnson.jpg"
...
<img src={johnsonImg} />

PS You can't look into the contents of src just by specifying a link like localhost:3000/src/components/foo/bar/example.file
If you need files with direct link access, put them in the "public" folder.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question