DEV Community

Shashank Soni
Shashank Soni

Posted on

A better way of importing Images (even SVGs) in React Js

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

footer-html-template

and now you want to convert it into a React component
Our traditional approach might be like this
react-footer-jsx

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.
Folder-structure

Here I have created a file called images.js which contains path of images as an object
importing images in image js file

You have to use .defaultafter 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,

importing img using image js file

Top comments (0)