Importing static images from your assets
folder into a React component can become a tedious task if you have to import multiple images, and it also changes your overall component's aesthetics . Let's understand it by looking at an example
and now you want to convert it into a React component
Our traditional approach might be like this
here we are using multiple import statements, suppose if we have more icons , our import statement may increase as well , and it will become messy & visually unpleasant (at least for me),
So I wanted to change this , and found a better way to deal with this situation.
I created a javascript file inside my assets folder, and imported all the images, related to project, into this file.
Here I have created a file called images.js
which contains path of images as an object
You have to use .default
after require
statement for importing SVGs otherwise it will not display the SVG . and for png/jpg/jpeg you can remove .default
and now , to use it, all you have to do is, import this images.js
file and use the image using . notation
,
Top comments (0)