DEV Community

Danielle Ye
Danielle Ye

Posted on • Updated on

React: Create onHover event with react hooks

Handling events in react is very similar to handling events on DOM elements. There are some syntax differences: in react, you need to use camelCase rather than lowercase for events name. Also, in react you need to pass in the event handler with JSX instead of a string. React supports syntheticEvents, with these events and hooks, we can easily create onHover event.

Example: show/hide an element on mouse hover
Here I will show a simple example, which will render "Hi!" when you hover over a button. In this example, I use useState hooks to create the initial hover state as false on the button. When onMouseEnter event happens, the hover state will be set as true, and when onMouseLeave event happens, the hover state will be set as false. <p>Hi!</p> element will only get rendered when our hover state is true.
Check out the code on CodeSandbox.

Top comments (0)