admin管理员组

文章数量:1296858

I want to change the color of react-icons when I hover over them with my mouse. With the code given below the icon only changes color when the mouse is hovering on the icon's lines. For instance with a mail icon the color only changes when the cursor hovers over the lines of the icon and not the empty spaces. How would I get the icon to change color if I hover over any part of it?

<AiOutlineMail size="80px"
    onMouseOver={({target})=>target.style.color="white"}
    onMouseOut={({target})=>target.style.color="black"}
/>

I want to change the color of react-icons when I hover over them with my mouse. With the code given below the icon only changes color when the mouse is hovering on the icon's lines. For instance with a mail icon the color only changes when the cursor hovers over the lines of the icon and not the empty spaces. How would I get the icon to change color if I hover over any part of it?

<AiOutlineMail size="80px"
    onMouseOver={({target})=>target.style.color="white"}
    onMouseOut={({target})=>target.style.color="black"}
/>
Share Improve this question asked Jul 1, 2021 at 17:06 veryconfusedrobotveryconfusedrobot 951 gold badge1 silver badge9 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Import the IconContext ponent from React-icons

import { IconContext } from "react-icons";

Then use this to wrap the icon(s)

<IconContext.Provider value={{ color: "#915eff", className: "contactIcon" }}>
      <FaLinkedin />
  </IconContext.Provider>

Then in the css folder, write this code

.contactIcon:hover {
  fill: #f2f735;}

Be sure to link the css file into the React app

Wrap the icon in a span or div and style that element. I'd also remend using CSS's :hover property rather than using JS to track the mouse.

<span class="changeColor">
  <AiOutlineMail size="80px"
    onMouseOver={({target})=>target.style.color="white"}
    onMouseOut={({target})=>target.style.color="black"}
  />
<span>

Then in CSS:

.changeColor {
  color: black;
}
.changeColor:hover {
  color: white;
}
  • Better way to achieve hover state on React icons is using css.
// using css and styled ponent

const ReactIcon = styled.div<{ color?: string; hoverColor?: string }>`
  display: flex;
  justify-content: center;
  align-items: center;
  svg {
    color: ${({ color }) => color ?? "black"};
  }
  svg:hover {
    color: ${({ hoverColor }) => hoverColor ?? "red"};
  }
`;
import { TiDeleteOutline } from "react-icons/ti";

...
// in react ponent
render() {
  ...
  return (
      <ReactIcon color="#a8a6a6" hoverColor="red">
         <TiDeleteOutline size={24}  />
      </ReactIcon>
  )
}

I have found a better way to do this. We can add class to the icon then we can just target it like this using css

 <LuThumbsUp className="thumbsUpIcon" size={16} />
  
.thumbsUpIcon {
    &:hover {
      path {
        stroke: #077789;
      }
    }
  }

本文标签: javascriptReact changing reacticon color on mouse hoverStack Overflow