Inline style an SVG imported as a ReactComponent

37 views Asked by At

When importing an SVG image as a react component, is it possible to apply inline styles to the svg element?

The following does not work, as the style gets applied to the element rather than the svg path:

import { ReactComponent as MyIcon } from "./my-icon.svg";

function MyComponent({}) {
  return <MyIcon style={{ fill: "blue" }} />; // Doesnt effect the SVG
}

enter image description here

I know that I can apply a className, then style the svg path in CSS, e.g:

<MyIcon className='my-icon' />
.my-icon {
  path {
    fill: blue;
  }
}

enter image description here

But the color is determined dynamically and is not known by the CSS (actually I'm using SCSS, but the same principle applies).

I understand that perhaps using a library like Emotion or Styled Components would solve this problem, but I'm wondering if it can be done inline without any additional packages.

0

There are 0 answers