How to Add a Hover Button in React?

Sometimes, we want to add a hover button in React.

In this article, we’ll look at how to add a hover button in React.

Add a Hover Button in React

To add a hover button in React, we can add a button that has the onMouseOver and onMouseOut props set to functions that run when we move our mouse over the button and move our mouse outside of it respectively.

In the functions, we set a state to track whether we hovered over the button or not.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [hover, setHover] = useState();

  const handleMouseIn = () => {
    setHover(true);
  };

  const handleMouseOut = () => {
    setHover(false);
  };

  return (
    <div>
      <button onMouseOver={handleMouseIn} onMouseOut={handleMouseOut}>
        {hover ? "foo" : "bar"}
      </button>
    </div>
  );
}

We have the hover state to track whether we hovered over the button or not.

And we set it to true in handleMouseIn and false in handleMouseOut.

We set onMouseOver to handleMouseIn and onMouseOut to handleMouseOut.

This way, hover is true when we hovered over the button and false otherwise.

In the button, we show ‘foo’ when hover is true and ‘bar’ otherwise.

Now when we hover over the button, we see ‘foo’ and we see ‘bar’ otherwise.

Conclusion

To add a hover button in React, we can add a button that has the onMouseOver and onMouseOut props set to functions that run when we move our mouse over the button and move our mouse outside of it respectively.

In the functions, we set a state to track whether we hovered over the button or not.