Reputation: 2590
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()
?
Upvotes: 32
Views: 42226
Reputation: 51
I put it in the "public" as it's intended for static files, while "src" or "components", are viable solutions as well too.
I do think by putting it in src or component they have to be imported into the component and to be used, also this can increase build size as it's being processed by Webpack.
Upvotes: 0
Reputation: 3662
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.
Upvotes: 43