Can't import SVG via ReactComponent
I need to import logo.svg, but I'll have to change its colors later on so I can't just import it and use it as src in <img> tag. So I've googled if it's possible to import it as a component and I've got people telling me to do it this way:
But I get a following error:
Uncaught SyntaxError: The requested module '/src/assets/logo.svg?import' does not provide an export named 'ReactComponent' (at App.jsx:3:10)
I'm in VS code and I can ctrl + click
on file path, and it takes me to my logo, so I know file path is not the issue.
If anyone experienced this issue and found solution please let me know, if not, do you know other way I can achieve what I want?11 Replies
I would suggest creating a whole new component only for that logo and provide the attributes that you want to customize as props. Import and use that instead of the raw logo.
I'd do it if I needed only one, but I need like 10 and I don't want to create new component for each svg...
I just found out that ReactComponent works if you use
create-react-app
to start the project and I'm using Vite so it must be something with that..It's working fine inside codesandbox.io... so it's possible its something to do with the tooling.
Can you try this svg just to confirm is not the actual file?
And also just to be sure, it's using this versions or higher?
Note: this feature is available with [email protected] and higher, and [email protected] and higher.This may also be useful: https://stackoverflow.com/questions/70309561/unable-to-import-svg-with-vite-as-reactcomponent
I know file is fine since it is working in app created with
create-react-app
so probably vite didn't include some of the dependencies I need for it
I don't even have react-scripts lolYeah I only read that you are using vite later and I'm guessing that must be it. That thread on stack overflow talks about using a plugin that will parse the svg and make it a component, so I think it's worth a try
It worked! I can use it as component now, thank you!
Nice! I'll try to remember that for when using Vite myself as well 🙂
Oof but I can't change fill property through JSX.. that's another issue lol
Well I made it work with custom properties for now... I'll try to find better solution tho..
Tried quickly again on codesandbox (which uses CRA) and it works fine. It must be again related to the plugin, either it must be configured somehow or it's a limitation it has...
I think when I use
fill
in component it puts fill attribute to svg
element, but I need it on the path
tag which is inside of it so that's probably why
Yeah I've just tried it in codesandbox with my svg and it doesn't work for meAhh I see that makes more sense.
I think, for something that is already a little more involved than simply importing an existing svg, maybe is worth creating your own implementation
At least, that would be my preference