Explain Codes LogoExplain Codes Logo

Reactjs and images in the public folder

javascript
webpack
image-management
asset-management
Anton ShumikhinbyAnton Shumikhin·Jan 8, 2025
TLDR

ReactJS provides a quick and easy way to access and display images stored in your public folder. By simply using the environment variable process.env.PUBLIC_URL, which points to your public directory, you're set to go:

<img src={`${process.env.PUBLIC_URL}/path/to/image.png`} alt="Description" />

This approach ensures that your application correctly locates and displays your images in both development and production environments, without any need for Webpack configuration.

When image paths are dynamic

In scenarios where you need to construct image path dynamically, like say displaying a user's profile picture or showing different icons based on the user's status, you can build the image path dynamically within the component:

const imageName = 'dynamicImage.png'; // because who doesn't love a surprise <img src={`${process.env.PUBLIC_URL}/path/to/${imageName}`} alt="Dynamic" />

Simpler asset management without Webpack

Avoiding the complexity of the Webpack asset management is indeed possible. With simple projects where you only need a minimal handling of assets, directly using the image paths is the way to go:

<img src="/images/myImage.jpg" alt="Direct" />

If you love the simplicity of a static file server, you'll appreciate this technique. No need for import statements or Webpack loaders.

The Art of folder organization

Keeping your project tidy and organized is as crucial as writing clean code. Consider grouping images that are related together. This will make them easier to locate and reference.

📁 React App └ 📁 public └ 📁 assets └ 📁 images └ 📁 icons └ 📁 banners

In a world full of mess, be a well-structured mess.

Advanced: using loaders with Webpack

Webpack shines when you need advanced asset management. For lazy loading or CDN hosting, you can use url-loader which allows images to be required in as URLs and provides size limits.

// loading image with Webpack url-loader import myImage from "./images/myImage.jpg"; // Webpack.config.js { test: /\.(png|jpe?g|gif)$/i, use: [ { loader: 'url-loader', options: { limit: 8192, }, }, ], }

Cross-Origin Resource Sharing (CORS) and external images

Images from a different origin typically face CORS restrictions. Be prepared to handle this by setting the necessary CORS policies on the server or using proxies.