skip to Main Content

I am mapping a data and sends to the component where it passes different colors for the background of the icon. But I want to change the color when I hover on the component that is rendered.

``
<div className="service-card--wrapper">
    <div className="service-card">
        <div className="service__icon" style={{backgroundColor:`${service.color}`}}>
            {service.icon}
        </div>
        <div className="service__title">{service.title}</div>
        <p className="service__para">{service.paragraph}</p>
        <button className="service__btn"><FaArrowRight/></button>
    </div>
</div>
``

I want to change the color when it hovers on the service-card but the CSS doesn’t overwrite the HTML inline-style, is there a way I can do this?

3

Answers


  1. With the assumption that you want styles from a CSS declaration to override the ones in the style attribute, you need the CSS to have a higher specificity. Unfortunately the only way to do that in this case (that I’m aware of) is to add !important to the style in the CSS (or remove the style attribute and use CSS for that as well).

    Using !important is usually reserved for certain definite overrides or as a last resort, so if you can avoid it that would be good. For example, if there aren’t too many options for service.color you could have a class for each color, and then assign the corresponding classname based on the variable instead of the color directly.

    Another option is to change the color programmatically in the JS in response to the corresponding mouse events.

    Login or Signup to reply.
  2. Sounds like you want to do something like this:

    .service__icon:hover {
    background-color: #desiredColor!important;
    }
    

    Note however that both inline style and the use of !important is not considered a good practice

    Login or Signup to reply.
  3. One possible approach to achieve this is to use

    • onMouseOver
    • onMouseOut
    handleMouseOver() {
      this.setState({ bgColor: service.color })
    }
    
    handleMouseOut() {
        this.setState({ bgColor: service.color2 })
    }
    <div className="service-card--wrapper">
        <div className="service-card">
            <div className="service__icon" 
                 onMouseOver={this.handleMouseOver} 
                 onMouseOver={this.handleMouseOut} 
                 style={{backgroundColor:this.state.bgColor}}>
                {service.icon}
            </div>
            <div className="service__title">{service.title}</div>
            <p className="service__para">{service.paragraph}</p>
            <button className="service__btn"><FaArrowRight/></button>
        </div>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search