#How can I use SVGR or another solution to import SVG inline in my React components on Astro?
12 messages · Page 1 of 1 (latest)
You can do this:
import svg from "./mysvg.svg?raw"
function MyComponent(props){
return <span dangerouslySetInnerHTML={{ __html: svg }} />
}
You'd have a <span> wrapper on all your svgs for this solution
dangerouslySetInnerHTML I have not needed to use this in a very long time
the naming is just a bit odd imo, I use it all the time!
What does the ?raw do?
It load assets as strings
Is it undocumented?
I can't find anything with a Google search or a search on the docs
It's a vite thing. You can see it mentioned here https://docs.astro.build/en/guides/styling/#raw-css-imports but the real source is here https://vitejs.dev/guide/assets.html#importing-asset-as-string 🙂
In our astro.config file, we import svgr from the vite-plugin-svgr package and pass it to vite.plugins so I believe an alternative to ?raw is using svgr directly.
Thanks for sharing this
Just to increment the response, in the case someone wants to adopt this answner like me, the code from astro.config file should look something like this:
import { defineConfig } from 'astro/config';
import svgr from 'vite-plugin-svgr'
export default defineConfig({
..., // your other integrations
vite: {
plugins: [svgr()]
}
});
From now, you can import your SVG's normally, like in the example bellow:
import { ReactComponent as DownArrow } from '@assets/icons/down_arrow.svg';