React Mouse onHover Event with Example

Published on Aug 11, 2020

The onHover event handler does not exist in React. But React provides event handlers to detect hover state for an element. In this article, we are going to learn how to use the handlers.

Table of Contents

  1. Show and Hide Content
  2. Change Background Color

Show and Hide Content

On hover an element, we can take an action. I’m going to show & hide content on hover a button. To do this, we’ll use 2 event handlers:

  • onMouseEnter
  • onMouseLeave

Let’s have a look at the example:

App.js
import React, { useState } from 'react';
import './App.css';

function App() {
  const [isShownHoverContent, setIsShownHoverContent] = useState(false);

  return (
    <div className="App">
      <button
        onMouseEnter={() => setIsShownHoverContent(true)}
        onMouseLeave={() => setIsShownHoverContent(false)}>
        Hover!
      </button>
      {isShownHoverContent && (
        <div>
          It works..!
        </div>
      )}
    </div>
  );
}

export default App;

Now if we hover the button, It works..! text will appear.

Change Background Color

In this example, we’re going to change background color of a div of mouse hover. Have a look:

App.js
import React from 'react';
import './App.css';

function App() {
  function changeBackgroundColor(e) {
    e.target.style.background = 'green';
  }

  return (
    <div className="App">
      <div onMouseOver={changeBackgroundColor}>Hover me!</div>
    </div>
  );
}

export default App;

There are two more hoverable event handlers named onMouseOut and onMouseLeave. You can test these.

That’s it. Thanks for reading. ?

Comments (0)