skip to Main Content

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

2

Answers


  1. what’s the issue with using CSS :hover?

    it works with svg elements.

        <>
          <div>
            <h1>Using with prop</h1>
            <Icon_5 className="icon icon-5" />
          </div>
        </>
    
    svg.icon-5 { stroke: #00ade9; }
    svg.icon-5:hover { stroke: #FF0000; }
    

    unless im missing something here

    Login or Signup to reply.
  2. Just give the parent of svg component an id or class and remove the props and stroke from all svg(s). then in css you can use :

    .parent svg{
    stroke:gray;
    }
    .parent svg:hover{
    stroke:red;
    }
    

    remove stroke from everywhere inside the svg, if the icons have a single color in all it’s sub-parts(path, rect, etc..).Otherwise, you may run into issues using both external and internal styling on svgs.
    Don’t use render() like that. It’s not supported in higher versions, use const root=ReactDom.createRoot(documnt.getElementById('root')); root.render(app());

    check the codeandbox example: https://codesandbox.io/s/svgfill-3-forked-nzjdc3?file=/index.js
    Check index.js and index.css files.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search