Div does not follow Mouse due to parent div

Viewed 50

I have a problem where the mouse does not follow the div closely due to parent div left and top. Assume parent.jsx is developed by another developer, and I solely can control child.jsx, is there a way for me to make the div follow the mouse?

Here's the parent jsx

import "./styles.css";
import Child from "./child";


export default function Parent() {


  return (
    <div
      style={{
        top: "25px",
        left: "20px",
        position: "relative"
      }}
    >
      <Child />
    </div>
  );
}

The child jsx

import "./styles.css";
import { useRef } from "react";

export default function Child() {
  const descBox = useRef(null);
  const handleMove = (e) => {
    console.log(e.clientX, e.clientY);
    descBox.current.style.left = `${e.clientX}px`;
    descBox.current.style.top = `${e.clientY}px`;
  };
  return (
    <>
      <div
        onMouseMove={handleMove}
        style={{
          height: "300px",
          width: "100%",
          backgroundColor: "red"
        }}
      ></div>
      <div className="dropdown1" ref={descBox}>
        123asdfsfdafffasdfasfdsajkj
      </div>
    </>
  );
}

The css for child

.dropdown1 {
  position: absolute;
  left: 150px;
  top: 10px;
  background: #2b4557;
  padding: 4px 8px;
  font-size: 12px;
  line-height: 18px;
  color: #fff;
}

Codesandbox to run the code.

1 Answers

As the child is positioned absolute within the relative positioned parent you can work out its left and top positions relative to the parent and use those.

This code adds a small offset to give a slight gap between the cursor and the child (which you may or may not want).

const handleMove = (e) => {
  const rect = e.target.getBoundingClientRect();
  const x = e.clientX - rect.left + 10;
  const y = e.clientY - rect.top + 10;
  descBox.current.style.left = `${x}px`;
  descBox.current.style.top = `${y}px`;
};
Related