Where should I put images files in React project?

Viewed 26433

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()?

enter image description here

1 Answers

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.

Related