D Dev Notebook

React Images

How to use images in React Project

1. Using Images in a public Folder

This is ideal for static images that don't need to be processed by the bundler.

<img src="/images/wallpaper.jpg" alt="wallpaper photo" />

2. Using Images in the src Folder

Ideal for images you want to import and optimize through the build process.

import taj from './images/tajmahal.png'

function Hello() {
    return(
        <>
            <img src={taj} alt="tajmahal photo" />
        </>
    )
}

3. Using Dynamic Images Imports

Useful when you need to dynamically set the image source.

const imageName = 'logo';
const imagePath = require(`./assets/${imageName}.png`);

function App() {
    return(
        <>
            <img src={imagePath} alt="Dynamic Logo" />
        </>
    )
}

4. Background Images in CSS

For background images, you typically use a CSS file:

.banner {
  background-image: url('../assets/wallpaper.png');
  width: 100px;
  height: 100px;
}
<div className="banner"></div>

On this page