Search code examples
javascriptreactjsonmouseoveronmouseout

Keep div visible to interact when using onMouseOver and onMouseOut in React.js


I'm working on a cart shopping on my website, when you hover, it should display another div just below the parent (with position absolute). The parent has position: relative and the div I want to show is inside him with position: absolute;

I did just that, but my problem is that, when I try to move the mouse on the div, its disappearing, onMouseOut is called and it also seems to be a little glitch when you hover the icon (its showing then hide then again showing)..

How can I fix?

Code: https://codesandbox.io/s/nifty-wiles-obqkmz


Solution

  • You don't need to have an if condition to check the state. This works just fine.

    import "./styles.css";
    import { useState } from "react";
    import { MyComponent } from "./MyComponent";
    
    export default function App() {
      const [show, setShow] = useState(false);
    
      return (
        <div className="App">
          <div
            className="parent"
            onMouseOver={() => setShow(true)}
            onMouseOut={() => setShow(false)}
          >
            <div className="cartIcon">
              <i class="material-symbols-outlined">shopping_cart</i>
            </div>
            {show && <MyComponent />}
          </div>
        </div>
      );
    }