I usually make images folder under src folder, so I access them through require require("images/sample.jpg")
in my components.
My friend who's learning React was struggling to load images and he made images folder under public like the below image. With that, he can access images without require()
, so he just does images/sample.jpg
. I thought I had it's required to use require()
to load images in React.
Is there no problem to put images folder under public? then why should we use require()
?
You can add image to image folder and set path to index file. Hope this will help you. Is there some impact on performance whether you require the image in the file you use it or whether you require globally via such a src/image/index.
In react best practices we keep an assets folder inside the src which may contain top-level CSS, images, and font files.
To display an image from a local path in React:Download the image and move it into your src directory. Import the image into your file, e.g. import MyImage from './thumbnail. webp' . Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" /> .
Adding images in the public folder and the src folder both are acceptable methods, however, importing images into your component has the benefit that your assets will be handled by the build system, and will receive hashes which improves caching/performance. You'll also have the added benefit that it will throw an error if the file is moved/renamed/deleted.
I should note that I believe the hashing functionality is out of the box with create-react-app but needs to be manually configured in Webpack otherwise.
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