okaryo.log

Controlling onHover Events in React | okaryo.log

Controlling onHover Events in React

    #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.

  • onMouseEnter: This event handler fires when the mouse cursor enters an element.
  • onMouseLeave: This event handler triggers when the mouse cursor leaves an element.

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

const Sample = () => {
  const [isHover, setIsHover] = useState(false);

  return (
    <div
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
    >
      {isHover ? "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.


Related Posts
Related Posts
Promotion

This site uses Google Analytics.