Controlling onHover Events in React

Introduction

The Chrome extension TabTabTab that I’ve been developing personally is built with React. In it, there’s a feature where the visibility of an element toggles based on mouse hover.

However, React doesn’t have an onHover event handler. I sometimes forget how to implement this functionality, so I’m writing it down here.

Implementation

As mentioned earlier, React does not have an onHover event handler. Instead, you can achieve similar functionality using the onMouseEnter and onMouseLeave event handlers.

You can update the state based on these events like this:

const Sample = () => {
  const [isHovered, setIsHovered] = useState(false);

  return (
    <div
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {isHovered ? "Hovered!" : "Not Hovered!"}
    </div>
  );
};

Conclusion

For other events aside from onMouseEnter and onMouseLeave, you can refer to the following page. It might be a good idea to take a glance.

Previous

Preventing GitHub Actions from Running Jobs on PRs from Specific Branches

Next

Automatically Generate Release Notes Using GitHub Actions When Tag Is Pushed

PR

Related Posts