A few days ago I saw a question in StackOverflow about how to change an SVG image's color. So I want to share a small tip to do it without the need of creating a component for each image that you have.
As the official docs say you can import an SVG icon as a react component just like this:
import { ReactComponent as Logo } from './logo.svg';
const App = () => (
<div>
{/* Logo is an actual React component */}
<Logo />
</div>
);
let's work with this SVG image as an example of our logo.svg
<path fill="#FFFFFF" stroke="#000000" stroke-width="2" d="M32.508,5.037C31.959,4.582,28.962,1.96,28.4,1.5a3.257,3.257,0,0,0-2.05-.5H8.447a3.263,3.263,0,0,0-2.05.5c-.56.462-3.557,3.086-4.106,3.54a2.216,2.216,0,0,0-.863,2.119c.147.98,3.516,24.286,3.6,24.841a1.228,1.228,0,0,0,1.206,1H28.562a1.228,1.228,0,0,0,1.206-1c.087-.553,3.457-23.861,3.605-24.841A2.22,2.22,0,0,0,32.508,5.037ZM17.4,20.508c-6.043,0-7.336-8.171-7.6-9.854h3.418c.513,2.455,1.682,6.656,4.186,6.656s3.674-4.2,4.186-6.656H25C24.735,12.337,23.442,20.508,17.4,20.508ZM4.693,6.344,8.1,2.778H26.7l3.4,3.566Z" transform="translate(-0.397)" />
We want to change the fill
and stroke
properties directly from the App
component. The tip is to change the fill
's and stroke
's value to current
so the color will be applied from the App
component. just like this:
<path fill="current" stroke="current" stroke-width="2" d="M32.508,5.037C31.959,4.582,28.962,1.96,28.4,1.5a3.257,3.257,0,0,0-2.05-.5H8.447a3.263,3.263,0,0,0-2.05.5c-.56.462-3.557,3.086-4.106,3.54a2.216,2.216,0,0,0-.863,2.119c.147.98,3.516,24.286,3.6,24.841a1.228,1.228,0,0,0,1.206,1H28.562a1.228,1.228,0,0,0,1.206-1c.087-.553,3.457-23.861,3.605-24.841A2.22,2.22,0,0,0,32.508,5.037ZM17.4,20.508c-6.043,0-7.336-8.171-7.6-9.854h3.418c.513,2.455,1.682,6.656,4.186,6.656s3.674-4.2,4.186-6.656H25C24.735,12.337,23.442,20.508,17.4,20.508ZM4.693,6.344,8.1,2.778H26.7l3.4,3.566Z" transform="translate(-0.397)" />
Then you can pass your colors from the App
component like this:
import { ReactComponent as Logo } from './logo.svg';
const App = () => (
<div>
{/* Logo is an actual React component */}
<Logo fill="red" stroke="green" />
</div>
);
This is my first post here! I hope you find this small tip useful.
Latest comments (13)
Interesting. It is what I was looking for about yesterday for my next mini project. Good explanation!
/Chaykov
Great!
can you explain about first line import { ReactComponent as Logo } ?
Great article, thank you!
It works with the 'stroke-width' too. Thank you.
Clean and simple solution. Thanks a ton!
❤️
Great stuff ! But what do we do if we have multiple colors in the svg , and would to change them all based on the themes chosen (primary /secondary colors) ? I think this can be used only with Single color SVG ?
Exactly. I want to change the colors of my SVG to red, green and grey on the basis of some conditions.
How can I achieve that?
Thanks bro
انقذت حياتي ههه
Wow if only I had known this sooner... Thanks a billion
Dude. Amazing stuff. Thanks