DEV Community

Shashank Soni
Shashank Soni

Posted on

2

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay