In my React Project, I want to change the stroke-color of my svg on hovering. I've achieved this by importing svg as ReactCompnent and then sending prop conditionally (useState hook to determine whether its being hovered or not). But I want to know if there is any other simple way round for this? Because, it will make the code lengthy if done for multiple svg icons. My code is as following:
import { useState } from "react";
import { render } from "react-dom";
import "./index.css";
import { ReactComponent as Icon_5 } from "./icon_5.svg";
function App() {
const [isHovered, setIsHovered] = useState(false);
const handleMouseEnter = () => {
setIsHovered(true);
};
const handleMouseLeave = () => {
setIsHovered(false);
};
return (
<>
<div>
<h1>Using with prop</h1>
<Icon_5
className="icon"
stroke={isHovered ? "#FF0000" : "#00ade9"}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
/>
</div>
</>
);
}
render(<App />, document.getElementById("root"));
I also tried applying color via css but the issue is that, each svg has different structure. For example, to completely change the stroke of this icon, I had to give it css this way:
.icon_1 path {
stroke: green;
}
.icon_1 line {
stroke: green;
}
.icon_1 rect {
stroke: green;
}
And this varies for each svg icon. So, this approach desn't seem to be a fit for this case.
Here is the codesandbox example for this: https://codesandbox.io/s/svgfill-3-w7kl7n?file=/index.js:0-684
what's the issue with using CSS
:hover?it works with svg elements.
unless im missing something here
Link to the sandbox here