Last updated: Apr 6, 2024
Reading time·2 min
To change the color of an SVG in React:
fill
and stroke
attributes on the SVG.fill
and stroke
props on the component.import {ReactComponent as MyLogo} from './my-logo.svg'; export default function App() { return ( <div> <MyLogo fill="black" stroke="yellow" /> </div> ); }
And here is the svg
for the example.
<svg width="400" height="400"> <circle cx="100" cy="100" r="50" stroke-width="5" /> </svg>
Notice that we didn't set the fill
and stroke
attributes on the svg
element.
Fill and stroke will only be applied when set through the component props if
they haven't been defined in the svg
.
fill
prop sets the color inside the object and the stroke
prop sets the color of the line drawn around the object.I've also written an article on how to render an Animated GIF in React.
Alternatively, you can paste your SVG into a component and take the colors as props.
function MyLogo({fill, stroke}) { // 👇️ Paste SVG into a component // Take fill and stroke colors as props return ( <svg fill={fill} stroke={stroke} width="400" height="400"> <circle cx="100" cy="100" r="50" stroke-width="5" /> </svg> ); } export default function App() { return ( <div> <MyLogo fill="black" stroke="yellow" /> </div> ); }
The code sample above achieves the same result, but we store the SVG directly in
a component instead of importing it from a file with an svg
extension.
Notice that the MyLogo
component takes the fill
and stroke
values as props
and applies them to the svg
element.
This should be your preferred approach if you don't have a loader in place that allows you to import SVGs as components.
Thanks to Robyn Van Gool for lots of corrections and helping me improve the article.