I know this has been answered before but no solutions are working for me. I want to render an svg file on an html page and access its code elements from javascript. I want to change the attributes of specific elements. Specifically I want to change add an attribute style="fill:#FFFFFF;". Later I will want to remove this. I want to access the element with the id property of the element. I tried doing this with a plethora of javascript code and rendering the svg as an img and an object and nothing works. Is this possible? If so how? Thanks in advance.
CodePudding user response:
You can create a react component for your SVG and control their properties with props in react way:
const SampleIcon = ({fill='red',backgroundColor='white', width='300', height='200'}) => (
<svg version="1.1"
width={width} height={height}
xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill={backgroundColor} />
<text x="150" y="125" font-size="60" text-anchor="middle" fill={fill}>SVG</text>
</svg>
)
Now use it:
const App = () => (
<div>
<SampleIcon fill='green' backgroundColor='#ff0'/>
<SampleIcon with={400} height={300}/>
</div>
)
CodePudding user response:
There is no way to change the fill property of an SVG you want to display in an img tag. However, you can change the filter
property.
So what you want to do is display the svg file like so:
<img src="./your.svg"/>
You have to give your img tag a classname (also, do not set the fill property inline).
Then you can simply apply a filter
and the color of the svg will be changed, like so:
.your-icon {
filter: invert(14%) sepia(95%) saturate(6069%) hue-rotate(360deg) brightness(108%) contrast(117%);
}
The above filter is red. Use this hex to filter converter to find the right color for you: hex to filter.
Here is a codesandbox demo.