How To Change SVG Color in React

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 = () => (
{/* Logo is an actual React component */}
);


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.