Explain Codes LogoExplain Codes Logo

React won't load local images

javascript
webpack
image-handling
performance-optimizations
Alex KataevbyAlex Kataev·Mar 4, 2025
TLDR

To display local images in React, import them into the component. Doing so uses Webpack to streamline their inclusion:

import myImage from './path/to/image.jpg';

Then, simply utilize the reference in your JSX:

<img src={myImage} alt="Description" />

Avoid the temptation to use a direct src string path; this process assures your images are correctly handled.

Loading images: the webpack way

Webpack revolutionises image handling through the require function, providing a professional way to load and bundle image resources effectively. This technique results in easily maintainable code:

<img src={require('./path/to/image.jpg').default} alt="Joke's in the alt tag" />

To achieve this, you need to adjust your Webpack setup to utilise url-loader and file-loader. The importance of this cannot be overstated:

  • url-loader offers the luxury of inline images as Data URIs for under a set byte size - a great way to minimize HTTP requests.
  • file-loader, in true buddy system fashion, handles file emissions. This buddy is invaluable when image sizes exceed the url-loader's threshold.

Install our loader buddies via npm. They love their jobs:

npm install --save-dev url-loader file-loader

Now, inform webpack about your new buddies:

module: { rules: [ { test: /\.(png|jpg|jpeg|gif)$/i, type: 'asset', parser: { dataUrlCondition: { maxSize: 8192 // 8KB, small enough to sneak through quietly } }, }, ], }

Node.js Express kindly ensures static assets are accessible from the public folder when properly told:

const express = require('express'); const app = express(); app.use('/static', express.static('public'));

And this is how the public sees it:

<img src="/static/path_to_image.jpg" alt="Public Image Ltd." />

Ensuring seamless integration

The devil is in the details: a simple mishap with the image file name or path might lead to load failure. Therefore, don't undermine the power of correct filename extension.

Properly handling routes in single-page React Router applications is like a limbo dance: the lower you go, the better you become. Don't let static asset paths tangle with your routes. Avoiding conflict is the best policy in server-side routing.

Image performance: getting it just right

Make magic by using smaller images as Data URIs – an enchanting way to streamline server requests. To craft this spell, set a byte limit in Webpack. All images under this limit will be transformed, like frogs to princes:

{ loader: 'url-loader', options: { limit: 10000, // Any images less than 10kb turns into a prince, or rather, base64 strings } }

Keep the image file size petite for ideal user experience - like a secret door in a garden, a small image can surprise and delight users, especially mobile ones.

Adding images to your code

The way you import an image into your component is like picking the perfect Instagram caption: it matters. Assess the final image path as the code will treat it as an image source string. Camera at the ready!

However, bear in mind that images need a static analysis at compile-time, not at the party time aka runtime. So, if possible, consider requiring images dynamically only when it doesn't overcomplicate Webpack's life.

Organizing assets in public folder

Like a librarian cataloguing books, store and access assets from the public folder. Libraries are for everyone and so is the public folder. Plus, if you use relative paths, it's even more secure and organized. It's like preventing someone from reaching a restricted section of the library. An ounce of prevention...

The efficiency of webpack

Bundling imported files (images, too) is a thing of beauty for Webpack. The process adds multiple layers of performance optimizations and keeps cache management in check, placing yet more emphasis on the way you import images as part of your module system.

Loaders: pick the right one for the job

Lastly, choose the right loader based on your project’s needs. Like a 90s game show, decide between url-loader and file-loader for handling different image scenarios.

And always, I mean always, refer to the create-react-app documentation. It has your back when it comes to handling image imports.

Visualization complete! 🎨

Troubleshooting: common issues and their solutions

Error: Incorrect paths

The Fix: Starting local image paths with ./ when importing is a declaration of love to the current directory that signifies: "I choose you!". If you don't, they may be mistaken for npm packages or modules.

Issue: Case sensitivity

The Fix: Files are like hipsters: they really care about case-sensitivity. Be consistent in your naming conventions.

Error: Image isn't getting bundled

The Fix: Get the image included in the output bundle by adding the image to the src/assets or public folder. Unless it's a super-secret image, then maybe it's best left unbundled.

Challenge: Conflicts with Webpack’s publicPath

The Fix: Avoid public tantrums, get your Webpack's publicPath set up right. Fostering a healthy relationship between server and assets avoids 404 custody battles.