Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add color to my svg image in react

Tags:

html

css

reactjs

I have a list of icons. I want to change the icons colors to white. By default my icons are black. Any suggestions guys?

I normally use 'fill: white' in my css but now that I am doing this in React... it's not working!

import React from 'react' import menuIcon from '../img/menu.svg'; import homeIcon from '../img/home.svg';   <ul>    <li>     <a href="/" className="sidebar__link">      <img src={menuIcon} alt="sidebar icon" className="sidebar__icon" />     </a>    </li>    <li>     <a href="/" className="sidebar__link">      <img src={homeIcon} alt="sidebar icon" className="sidebar__icon" />     </a>    </li> </ul>    .sidebar__icon {  fill: #FFFFF;  width: 3.2rem;  height: 3.2rem; } 
like image 700
Deejay Avatar asked Feb 04 '19 15:02

Deejay


People also ask

How do I change the color of an SVG image?

Edit your SVG file, add fill="currentColor" to svg tag and make sure to remove any other fill property from the file. Note that currentColor is a keyword (not a fixed color in use). After that, you can change the color using CSS, by setting the color property of the element or from it's parent.

Can SVG files have color?

Scalable Vector Graphics or SVG's are graphics that are defined using an XML text file. This means they can be opened with a text editor and the HEX code that determines the colors can be changed. First, the HEX value of the color must be known.


2 Answers

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> ); 
like image 136
Nasser Abachi Avatar answered Sep 24 '22 15:09

Nasser Abachi


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> 
like image 31
Fpunkt Avatar answered Sep 22 '22 15:09

Fpunkt