Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading