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

31 Views Asked by At

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

3

There are 3 best solutions below

0
hari prakash On BEST ANSWER

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>
  );
}
0
Oktay Yuzcan On

Use onMouseLeave instead of onMouseOut

0
roanjain On

You simply need to update your code to use onMouseEnter and onMouseLeave.