React Mouse onHover Event

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.

Leave a comment

Your email address will not be published. Required fields are marked *