DEV Community

Cover image for The Best Way to import images in ReactJs, and NextJs 🚀
vito.mohagheghian
vito.mohagheghian

Posted on • Updated on

The Best Way to import images in ReactJs, and NextJs 🚀

Importing images was always a pain in the neck 👔 especially importing them with long paths in multiple lines, so I searched 🔎 a lot to find the best ones and then tested them to ensure, they were the best to use in daily projects 👍. So after spending hours 🕝 using it on different projects, I finally discover the answer for daily usage. 😀

certainly, it's not the best answer for use in different projects, so I will create posts for each situation soon.

without any interrupting let's get into it. ✍️

Make Index file

In the public folder create a new file index.js, or index.tsx, or any folder you want to export its existing images.

there are lots of third packages, which you can use to import, but I prefer to import them manually! lightness.

Import/Export Images

then export them like below:

Image description

Import In React Components

and instead of importing images with long paths, now you import them like below:

Image description

SVGs

You can also make file SVGs, and return SVG elements like react components.

Image description

Conclusion

It may not be the best for specific projects ⚠️, but for regular react projects is OK.

If you know a better way than this one 🕵️. please 🙏 comment it 💭 below to let others and I know 👍.

keep in touch 👋

Keep Coding Y'All 👨🏻‍💻

Top comments (6)

Collapse
 
codeofrelevancy profile image
Code of Relevancy

Great article..

Collapse
 
naucode profile image
Al - Naucode

Great article, you got my follow, keep writing!

Collapse
 
vitomohagheghian profile image
vito.mohagheghian

Thank you, 😍🥰🙏

Collapse
 
erinkahn profile image
Erin Kahn

I don't understand looking at how you exported and then imported. You exported image.png. Then you imported Image1 and Image 2 from an icons folder? But you made an index file in the public folder. When did you make an icons folder?

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
vitomohagheghian profile image
vito.mohagheghian

Thanks 💙