The Best Way to import images in ReactJs, and NextJs π
vito.mohagheghian
Posted on February 4, 2023
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:
Import In React Components
and instead of importing images with long paths, now you import them like below:
SVGs
You can also make file SVGs, and return SVG elements like react components.
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 π¨π»βπ»
Posted on February 4, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.