Home > Software design >  Hide and show element onMouseOver and mouseOut in React
Hide and show element onMouseOver and mouseOut in React

Time:10-20

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" onm ouseOver={handleMouseOver} onm ouseOut={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

CodePudding user response:

Need to hide the first element too

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

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

Demo

CodePudding user response:

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"
  onm ouseOver={handleMouseOver}
  onm ouseOut={handleMouseOut}
>
  {isHovering && (
    <div>
      <h2>Only visible when hovering div</h2>
    </div>
  )}
  {!isHovering && (
    <div>
      <h2>Only visible when not hovering div</h2>
    </div>
  )}
</div>
  • Related