Skip to main content

Images

Using images in a React application can be done in several ways:

1. Importing Images

You can import an image file and use it in your component. This is the most common method when using Create React App or a similar build setup that supports the import of image files.

import React from 'react';
import logo from './logo.png'; // Importing the image

function App() {
return (
<div>
<img src={logo} alt="Logo" />
</div>
);
}

export default App;

2. Public Folder

If you have images in the public folder, you can refer to them by their relative path from the public folder. This method doesn't require importing the image.

function App() {
return (
<div>
<img src="/images/logo.png" alt="Logo" />
</div>
);
}

3. Inline Base64 Images

You can also use Base64 encoded images directly in your JSX.

function App() {
return (
<div>
<img src="data:image/png;base64,iVBORw0KGg..." alt="Logo" />
</div>
);
}

4. Dynamic Image Paths

If you need to dynamically set the image path, you can do so using a variable.

function App() {
const imagePath = "https://example.com/logo.png";

return (
<div>
<img src={imagePath} alt="Logo" />
</div>
);
}

5. SVG Images

You can also directly include SVGs in your JSX.

function App() {
return (
<div>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="black" strokeWidth="3" fill="red" />
</svg>
</div>
);
}

6. Background Images in CSS

If you're using a CSS file, you can set background images in the usual way.

/* App.css */
.background {
background-image: url('./images/background.jpg');
}
// App.js
import './App.css';

function App() {
return (
<div className="background">
{/* content */}
</div>
);
}

Each of these methods has its own use-cases, and you can choose the one that best fits your needs.

info

While bundling images if an image size is less than 9.7kb it would be converted to base 64 code and would be part of bundle file. If it is bigger than image would be moved to /static/media folder and used as image file.