Change the color of an SVG in React

avatar
Borislav Hadzhiev

Last updated: Apr 6, 2024
2 min

banner

# Change the color of an SVG in React

To change the color of an SVG in React:

  1. Don't set the fill and stroke attributes on the SVG.
  2. Import the SVG as a component.
  3. Set the fill and stroke props on the component.
App.js
import {ReactComponent as MyLogo} from './my-logo.svg'; export default function App() { return ( <div> <MyLogo fill="black" stroke="yellow" /> </div> ); }
The code for this article is available on GitHub

And here is the svg for the example.

my-logo.svg
<svg width="400" height="400"> <circle cx="100" cy="100" r="50" stroke-width="5" /> </svg>

react change svg color

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.

The 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.

# Create a component that renders the SVG taking the colors as props

Alternatively, you can paste your SVG into a component and take the colors as props.

App.js
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> ); }

taking colors as props in custom component

The code for this article is available on GitHub

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.