Making multiple react icons changing different color on hover using JSX

Viewed 24

I'm trying to make different icons in the footer, with different brands. I want them to change color when I'm hovering over them. I've created a CSS class with the hover pseudo-class, but I want to make a sort of parameter in my JSX file which tells the class that a certain color should be applied to a certain icon This Is my CSS class:

.icon-background {
    color: rgb(49, 45, 44, 0.8);
}

.icon-background:focus,
.icon-background:hover {
    background-color: var(--color);
    transition-duration: 0.2s;
    padding: 2.5px;
}
1 Answers

An easy way to accomplish this would be through utility css classes. For instance, you could insert an icon in the jsx file like this:

<div className="blue default_icon">ICON</div>

With corresponding css:

.blue:hover, 
.blue:focus {
  background-color: #0000ff;
}

.default_icon {
  color: rgb(49, 45, 44, 0.8);
}

.default_icon:hover {
  transition-duration: 0.2s;
  padding: 2.5px;
}

A better way you could do this is with React state. Basically, create an icon component and pass a color as a prop. This will be much less css and will be more scalable:

import { useState } from 'react';

const Icon = (props) => {
   const hoverColor = props.hoverColor;
   const [isHover, setIsHover] = useState(false);

   const handleMouseEnter = () => {
      setIsHover(true);
   };

   const handleMouseLeave = () => {
      setIsHover(false);
   };

   const hoverStyle = {
      backgroundColor: isHover ? hoverColor : "defaultColor",
   };

   return (
         <div
            style={hoverStyle}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
         >
            ICON
         </div>
   );
};

export default Icon;

You can then use the icon anywhere in your project like so:

<Icon hoverColor={"#0000ff"} /> // This would turn blue on hover
Related