How to change the color of an SVG dynamically with props in React?

Asked

Viewed 96 times

2

I’m trying to change the color of an SVG through props, but I’m not getting it.

My component Hexagon that in which I receive the color via props and check with a switch:

function Hexagon({ size, text, color }) {
  let hexagonColor;
  switch (color) {
    case "green2":
      hexagonColor = style.green2;
      break;
    default: {
      hexagonColor = style.green2;
    }
  }
  return (
    <div className={style.container}>
      <p className={style.hexagonText}>{text}</p>
      <img
        src={hexagon}
        alt="Hexagon"
        className={hexagonColor}
      />
    </div>
  );
}

This is where I call the component and passing the color:

function Navbar() {
  return (
    <div >
      <div>
        <Hexagon text="Planejar" color="green2" />
        <Hexagon text="Planejar" color="green2" />
      </div>
      <div>
        <Hexagon text="Planejar" color="green2" />
        <Hexagon text="Planejar" color="green2" />
      </div>
    </div>
  );
}

Here is my CSS file:

.green2 path {
  fill: #8e18d2;
}

I already checked and the class really appears in the component, see in the image below

hexagon

  • 1

    where is style: (style.green2)?

  • 1

    I think a SVG that you embed as <img src=".... svg"> vc can’t change color like that, at least not in html.... give a look here sometimes help you https://answall.com/questions/286686/mudar-a-cor-de-um-svg-por-um-bot%C3%a3o/286696#286696

  • novic o style.green2 is in my css file

  • 1

    You can try using SVG as a component with SVGR. The selector .green2 path won’t work because the tag img will not render the SVG inside it, you can see by the own tag print that has no <svg> or <path> there.

  • 1

    @Pedro if it is a css attached to the component, it is not only put the name ?

  • @ Rafael Tavares has never seen this SVGR, I’ll take a look, is that I n wanted to have q install a lib so to do this

  • @Novic I understood very well what you said ;-;

  • You had personal reason, as img he n rendenderiza never, I had to import as a component same, Thank you all for the help. put the resolution in the comments

  • 1

    svg is nothing more than an XML file, you can set a javascript color on it, example: <object class="svgClass" type="image/svg+xml" data="image.svg"></object> -> document.querySelector(".svgClass").getSVGDocument().getElementById("svgInternalID").setAttribute("fill", "red")

Show 5 more comments

1 answer

1

I was able to solve only important svg as a component, because img does not render svg on the screen, I did it as follows

import { ReactComponent as HexagonSVG } from "./hexagon.svg";

Right below, it was just using it as a component itself, that way

<HexagonSVG
        className={`${style.hexagon} ${hexagonColor} ${hexagonSize}`}
 />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.