Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save images for React application

I have a react application (generated withcreate-react-app so with webpack) that uses a JSON file to retrieve the text content and image URL or relative path. What's the best way to save these images provided that the content in the JSON might change over time:

  1. Import all images mentioned in the JSON in the project and save them in the src folder.
  2. Save the images in other services like S3 and then quote the URL in the JSON file.
  3. Save the images in the public folder.
like image 857
ocram Avatar asked Oct 21 '25 10:10

ocram


1 Answers

Any of these approaches will work, however, each has their own advantages and disavantages.

src folder

Images stored here have the added bonus of being able to be imported as a JavaScript module:

import React from 'react';
import logo from './logo.png'; // Tell Webpack this JS file uses this image

console.log(logo); // /logo.84287d09.png

function Header() {
  // Import result is the URL of your image
  return <img src={logo} alt="Logo" />;
}

export default Header;

Webpack will include imported files in the bundle, and images under ~10K will be converted to data URIs to avoid extra network requests. Missing files will also cause compilation errors rather than 404s, and filenames will have hashes to bust cache when the content changes.

More info: https://create-react-app.dev/docs/adding-images-fonts-and-files/

Other services like S3

This works just like any other external server or CDN.

public folder

Files in public will not be bundled by Webpack, and so do not get any post-processing treatment like minification. Additionally, you will need to use the PUBLIC_URL environment variable. Other files in the public folder such as public/index.html would have this:

<img src="%PUBLIC_URL%/logo.png">

From JavaScript code in src:

render() {
  return <img src={process.env.PUBLIC_URL + '/logo.png'} />;
}

The public folder is helpful when you need to reference images with specific file names.

More info: https://create-react-app.dev/docs/using-the-public-folder/

like image 122
Ryan Avatar answered Oct 23 '25 01:10

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!