Home > front end >  How to fetch image names from database and display them in react app
How to fetch image names from database and display them in react app

Time:06-23

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

CodePudding user response:

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.

CodePudding user response:

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="" />
  • Related