Hide and show element onMouseOver and mouseOut in React

2.2k views Asked by At

using this code here:

import {useState} from 'react';

const App = () => {
  const [isHovering, setIsHovering] = useState(false);

  const handleMouseOver = () => {
    setIsHovering(true);
  };

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

  return (
    <div>
      <div>
        <div id="target" onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
          Hover over me
        </div>

        {isHovering && (
          <div>
            <h2>Only visible when hovering div</h2>
          </div>
        )}
      </div>
    </div>
  );
};

export default App;

I can easily show and hide a div when the mouse is over/out the target div. But, what I need, is that when the mouse is over the target, the target itself disappears, and appears the second div and when the mouse is out of the second div, the target appears again.

Here's a codesandbox https://codesandbox.io/s/thirsty-babycat-e2c1hh?file=/src/App.js

thank you very much

2

There are 2 answers

0
Sachila Ranawaka On BEST ANSWER

Need to hide the first element too

  {!isHovering && (
      <div
        id="target"
        onMouseOver={handleMouseOver}
        onMouseOut={handleMouseOut}
      >
        Hover over me
      </div>
    )}

    {isHovering && (
      <div
        onMouseOut={() => {
          setIsHovering(false);
        }}
      >
        <h2>Only visible when hovering div</h2>
      </div>
    )}

Demo

0
zmehall On

You could wrap the entire block in an element that handles the events, then place both versions of the element (hovering/not hovering) inside.

<div
  id="target"
  onMouseOver={handleMouseOver}
  onMouseOut={handleMouseOut}
>
  {isHovering && (
    <div>
      <h2>Only visible when hovering div</h2>
    </div>
  )}
  {!isHovering && (
    <div>
      <h2>Only visible when not hovering div</h2>
    </div>
  )}
</div>