Ackman
Ackman

Reputation: 1592

how to change color of a svg source in a img tag?

I am trying to change the color of an svg icon from black to white when a color prop is provided.

export class CategoryIconComponent extends React.Component {


static displayName = 'CategoryIcon';

  state = { icon: null };

  static propTypes = {
    title: PropTypes.string,
    color: PropTypes.string,
  };

  static defaultProps = {
    title: null,
    color: '#fff',
  };

  componentDidMount() {
    const { title } = this.props;

    if (getTopCategoryIcon('Concrete Contractors') != null){

    if(typeof getTopCategoryIcon('Concrete Contractors') === 'string'){
      this.setState({ icon: getTopCategoryIcon('Concrete Contractors') });
    }

   else{
      getTopCategoryIcon(title).then((newIcon) => {
        this.setState({ icon: newIcon });
      });
    }
  }
}

  render() {
    const { icon } = this.state;
    const { color } = this.props;

    return (
      icon && (
        <TextIconContainer>

           // I want to be able to change color of the icon from black to white via color prop here
           // something like
          <img src={icon} width={25} height={25} color={color} />
        </TextIconContainer>
      )
    );
  }

Is there a css way to do it? or any other way I can tap into the svg component and change it?

enter image description here

Upvotes: 3

Views: 3988

Answers (1)

Toby
Toby

Reputation: 13385

I don't believe there is a way to do it with the SVG placed via an image tag, but I was able to achieve this by using SVGs as simple React components:

import React from 'react'

export const MySvg = ({ color }) => (
  <svg style={{ fill: color }}>
    ...
    ...
  </svg>
)

And then using in your component:

<MySvg color={color} />

I don't see this as a workaround, or a hack - quite the opposite. I have been able to achieve some impressive theming and customization using this technique.

Obviously you could extend this method to manipulate the fill directly:

export const MySvg = ({ color }) => (
  <svg fill={color}>
    ...
    ...
  </svg>
)

Upvotes: 2

Related Questions