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:
src
folder.public
folder.Any of these approaches will work, however, each has their own advantages and disavantages.
src
folderImages 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/
This works just like any other external server or CDN.
public
folderFiles 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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With