Galbert
Galbert

Reputation: 227

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

Upvotes: 0

Views: 47

Answers (3)

hari prakash
hari prakash

Reputation: 26

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>
  );
}

Upvotes: 1

roanjain
roanjain

Reputation: 1252

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

Upvotes: 1

Oki
Oki

Reputation: 3300

Use onMouseLeave instead of onMouseOut

Upvotes: 1

Related Questions