SVGR in Astro: Convert SVGs to React Components Easily
Use SVGs as components in both Astro and React components with and without installing packages .SVGs as props and others more tips.
Before we start the installation process, I would like to discuss it's need. While working with the Astro framework, it is easy to use SVG as Astro components, but when we create React components using SVG, things change. When we jump into any framework, the way we used to do things may differ. So, I felt like writing this blog. Now, let's directly see how we can use SVGs as components in both .astro and .tsx files within our Astro project. Learn to use it with or without setup, so be sure to read the blog till the end for more tips on using SVG.
1.1 Example of it using in Astro given below : -

So, this is how we can do it in Astro—it's really simple. In .astro files, we can also pass SVGs as props, although the typing is a little different. Code given below : -

Now, if we want to use the same approach in .tsx files, we need to install an additional package in our Astro project. Below is the installation and configuration process : -
Install the packages :
Using yarn yarn add -D vite-plugin-svgr
Using npm npm install -D vite-plugin-svgr
Then , after installing the packages import svgr on astro.config.js : -

Lastly, to use SVGs as icons in React components, we need to configure the types so Astro knows how to handle them. Just like using logo.svg?react, we simply add ?react to the SVG import. Everything else remains the same.
Create a new file at public/types/svg.d.ts : -

With all this setup complete, you're now fully ready to use SVGs in your React components.
1.2 Example of it using in React Component given below : -

So, hurray! You’ve now learned how to use SVGs as React components in Astro. These types of setups provide a little extra power and flexibility when working with icons.
Note : If it still doesn't work then restart the server or close your VS-Code and open again.
1.3 Example of it using in React Component without installation below : -

So, looking at the image above, we have directly used an SVG in our React components. Now, we can use it in any component as a logo by simply importing it as Logo.tsx.
Extra tips: When working with SVGs, you can change their color by replacing fill="#D46900" with `fill="currentColor" and sometimes if we don't have fill there is stroke="currentColor" . This allows you to control the color wherever you use the SVG, for example:
<Logo className="text-red-500" />
Similarly, to adjust the width and height, remove the width and height properties from the SVG and use className instead:
<Logo className="w-4 h-4" />
Thanks for reading the blog till the end! If you have any doubts, feel free to ask. Thank you.
Comments ()