javascriptreactjsonmouseoveronmouseout

Hide and show element onMouseOver and mouseOut in React


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


Solution

  • 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