Issues with :hover effect in React

Hello,

I’m working on the React JS Calculator [link to Codepen] project right now, and I’m having trouble getting the :hover effect to work.

Here is my React Component:

class Keypad extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div className='buttons' style={cssKeypad}>
        <div style={cssDblButton}>AC</div>
        <div style={cssButton}>+</div>
        <div style={cssButton}>-</div>
        <div style={cssButton}>1</div>
        <div style={cssButton}>2</div>
        <div style={cssButton}>3</div>
        <div style={cssButton}>-</div>
        <div style={cssButton}>4</div>
        <div style={cssButton}>5</div>
        <div style={cssButton}>6</div>
        <div style={cssButton}>+</div>
        <div style={cssButton}>7</div>
        <div style={cssButton}>8</div>
        <div style={cssButton}>9</div>
        <div style={cssDblVertB}>=</div>
        <div style={cssDblButton}>0</div>
        <div style={cssButton}>.</div>
      </div>
    )
  }
};

And I’m trying to add the :hover effect using a CSS class like this:

.buttons:hover {
  background-color: #90EE90;
}

The :hover effect is not working. Is this because the style={cssButton} attribute has precedence over the className attribute?

I’ve done some research and others have said that I need to use event handlers for onMouseOver and onMouseOut, but that seems like a lot of code just for a hover effect.

The onMouseOver did work when I did event.target.style.backgroundColor = '#90EE90', but changing the color back onMouseOut would require additional conditionals depending on whether the original button color was blue or red.

I’m wondering if there is a simpler way to do this.

Thank you!

Do you want the hover effect on the individual “buttons” or on the wrapper div?

It’s because you are setting the background-color property on the “button” element directly and so using :hover psuedo-class on the “button” isn’t going to override that background-color. One way to fix this is to add !important to the background-color in the hover CSS. I’m not sure everyone would agree this is the best solution though.

You may have noticed that I put “button” in quotes above. That’s because you are calling these buttons but they aren’t really buttons semantically. You really should use an actual button element for these. It will make them much more accessible by default.

1 Like

@bbsmooth

Thank you for the advice! I had a partially-formed thought that adding the className to the wrapper div and then doing some event.target thing would work with the bubbling action.

The !important tag worked. I suppose that will have to do, for now.

And I guess I should go back and change the buttons to literal <button> elements.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.