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
where is
style
: (style.green2
)?– novic
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
– hugocsl
novic o style.green2 is in my css file
– Pedro
You can try using SVG as a component with SVGR. The selector
.green2 path
won’t work because the tagimg
will not render the SVG inside it, you can see by the own tag print that has no<svg>
or<path>
there.– Rafael Tavares
@Pedro if it is a css attached to the component, it is not only put the name ?
– novic
@ 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
– Pedro
@Novic I understood very well what you said ;-;
– Pedro
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
– Pedro
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")
– Ivan Ferrer
Take this example
– Ivan Ferrer