How do I add color to my svg image in react
use your SVG as a component, then all the SVG goodness is accessible:
const MenuIcon = (props) =>(
<svg xmlns="http://www.w3.org/2000/svg" fill={props.fill} className={props.class}></svg>
)
And in your render
<li>
<a href="/" className="sidebar__link">
<MenuIcon fill="white"/>
</a>
</li>
I use this approach to avoid the need of creating a React component for each icon. As the docs say you can import the SVG file as a react component.
import { ReactComponent as Logo } from './logo.svg';
const App = () => (
<div>
{/* Logo is an actual React component */}
<Logo />
</div>
);
If you want to change the fill property you have to set your SVG fill
's value to current
then you can use it like this:
<svg fill="current" stroke="current" ....> ... </svg>
import { ReactComponent as Logo } from './logo.svg';
const App = () => (
<div>
{/* Logo is an actual React component */}
<Logo fill='red' stroke='green'/>
</div>
);
I found an interesting solution to this problem. Don't know if it works in all cases though... Okay so I have an svg that import like:
import LockIcon from "../assets/lock.svg"
and then render it as:
<LockIcon color={theme.colors.text.primary} />
and then in lock.svg I just add fill="currentColor"
in the svg tag.
Hopefully this can useful for some of you.
You can change css of svg by accessing g or path. Starting from create-react-app version 2.0
import React from 'react'
import {ReactComponent as Icon} from './home.svg';
export const Home = () => {
return (
<div className='home'>
<Icon className='home__icon'/>
</div>
);
};
.home__icon g {
fill: #FFFFF;
}
.home__icon path {
stroke: #e5e5e5;
stroke-width: 10px;
}