0

The images are stored in the client/public/images folder. And the file name and extension is fetched from a mysql database. How do I write the src attribute of the img element to display the images.

<img src={`%PUBLIC_URL%/images/${portraitFile}`} alt='' />

this is not working

My project structure:

- public
   -images
      - portrait.jpg
- src
   - components
       - image viewer component
- App.js
2
  • Are you using a react app or next.js app or vitejs app? Commented Jun 23, 2022 at 8:18
  • I'm using react app Commented Jun 23, 2022 at 9:04

3 Answers 3

2

You are using wrong syntax as per CRA app. Use the following:

<img src={require("../images/${portraitFile}").default} alt="" />

Give the path to your images folder.

If the images are in public folder. you can write:

<img src={`../images/${portraitFile}`} alt='Portrait' />

Notice the backticks since you are using template literal syntax.

Sign up to request clarification or add additional context in comments.

3 Comments

<img src={require('../../public/images/${portraitFile}').default} alt='Portrait' /> I've done this since its in the public/images folder, but the console gives this error Cannot find module './'
In that case you can just write: <img src={../images/${portraitFile}} alt='Portrait' /> I have updated my answer. Hope it helps.
I've got it. It was supposed to be ` <img src={'/images/${portraitFile}'} alt='Portrait' width='70%'/>`. Thank you very much
1

If your project structure is like this:

- public
  - images
    - portrait.png
- src
  ...
  - components
  ...
  App.js

and you put your image tag inside App.js, you can source the image like this:

<img src={`../images/portrait.png}`} alt='' />

If you put your image inside your src directory:


- src
  - assets
    - images
      - portrait.png
  - components
  ...
  App.js

at the app you can import like this:

import Logo from "./assets/images/logo192.png";

and render using the imported Logo:

<img src={Logo} alt="" />

1 Comment

I edited the question and added my project structure. How should I write the src attribute
0

I've got it guys. It was supposed to be:

<img src={`/images/${portraitFile}`} alt='Portrait' width='70%'/>

since every component is rendered in the index.html file, I should've had made the src structure according to the index.html file. That was it

Comments

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.