15_Accessing Static Images in React - Maniconserve/React-Wiki GitHub Wiki
There are two places to store images in a React app, and each is accessed differently.
Images placed in public/ are served as-is — no processing, no import needed. Reference them using a path starting from /.
public/
logo.png
banner.jpg
function App() {
return (
<div>
<img src="/logo.png" alt="Logo" />
<img src="/banner.jpg" alt="Banner" />
</div>
);
}✅ Simple — no import needed.
✅ Good for large files, favicons, and images referenced in index.html.
❌ Not optimised or fingerprinted by the build process.
❌ If the file is missing, you get a broken image at runtime — no error during build.
Images placed inside src/ must be imported like any other file. The build tool (Webpack) processes them, optimises them, and generates a unique filename.
src/
assets/
logo.png
banner.jpg
import logo from './assets/logo.png';
import banner from './assets/banner.jpg';
function App() {
return (
<div>
<img src={logo} alt="Logo" />
<img src={banner} alt="Banner" />
</div>
);
}✅ Build-time error if the file is missing — caught early.
✅ Webpack optimises and fingerprints the file (e.g. logo.a3f2c1.png) for caching.
✅ Recommended for images used inside components.
If the image path comes from a variable or prop, use require() for images inside src/.
function Avatar({ filename }) {
return <img src={require(`./assets/${filename}`)} alt="Avatar" />;
}
// Usage
<Avatar filename="profile.png" />Or if you have a list of images:
import cat from './assets/cat.png';
import dog from './assets/dog.png';
import bird from './assets/bird.png';
const animals = [
{ name: 'Cat', image: cat },
{ name: 'Dog', image: dog },
{ name: 'Bird', image: bird },
];
function AnimalList() {
return (
<ul>
{animals.map(animal => (
<li key={animal.name}>
<img src={animal.image} alt={animal.name} />
<p>{animal.name}</p>
</li>
))}
</ul>
);
}| Situation | Where to put the image |
|---|---|
| Used inside a component |
src/assets/ — import it |
Referenced in index.html
|
public/ |
| Favicon or manifest icon | public/ |
| Large files (videos, PDFs) | public/ |
| Image path is dynamic/unknown at build time | public/ |
| Method | Syntax |
|---|---|
public/ folder |
<img src="/filename.png" /> |
src/ folder |
import img from './assets/img.png' then <img src={img} />
|
Dynamic with require
|
<img src={require('./assets/' + filename)} /> |