Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put images files in React project?

Tags:

reactjs

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

like image 311
Jae P. Avatar asked Nov 07 '18 14:11

Jae P.


People also ask

Where do images go in React native project?

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.

Where should I place assets in React?

In react best practices we keep an assets folder inside the src which may contain top-level CSS, images, and font files.

How do I display images in React?

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" /> .


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.

like image 76
Keith Brewster Avatar answered Oct 23 '22 09:10

Keith Brewster