Trying to display a custom menu at the location of a mouse click within a div, but it doesn't seem to be working as expected. The visibility logic works fine, but when clicking on the div, the menu only opens under the Typography element. Should the Menu be positioned elsewhere?
Check out how it's currently displaying - menu under Typography. The menu appears in the same place regardless of where I click inside the div, when ideally it should show up at the exact position of the mouse click.
Below is an example of the current setup with some code removed for clarity:
interface PositionState {
x: number;
y: number;
}
function WebAppTypeCard({
id,
name,
image,
description,
image_url,
}: WebAppCardTypeProps) {
const [visible, setVisible] = useState<boolean>(false);
const [webApps, setWebApps] = useState<IWebApp[]>([]);
const [position, setPosition] = useState<PositionState>({ x: 0, y: 0 });
useEffect(() => {
fetch(`${process.env.REACT_APP_API_URL}/webapp/read_all/${id}`, {
headers: headers,
})
.then((data) => {
return data.json();
})
.then((res) => {
setWebApps(res);
});
}, []);
const handleClick = (e: any) => {
if (webApps.length > 1) {
setPosition({ x: e.clientX, y: e.clientY }); // <--- Set position and make menu visible on mouse click
console.log(position);
setVisible(true);
} else {
window.open(selectedWALink);
}
};
const handleMouseLeave = () => {
setVisible(false);
};
const style = (x: number, y: number) => {
return {
top: x,
left: y,
};
};
const Menu = () => {
return (
<div style={style(position.x, position.y)}>
{webApps.map((a) => {
return (
<div key={a.id} onClick={() => handleMenuClick(a.link)}>
{a.name}
</div>
);
})}
</div>
);
};
return (
<div className="cardContainer" onMouseLeave={handleMouseLeave} onClick={handleClick}>
<div>
<div
style={{
display: "flex",
justifyContent: "center",
}}
>
<img
className="appImg"
src={image_url}
width={65}
height={65}
style={{ paddingTop: 15 }}
alt="Image not found"
/>
</div>
<div
style={{
paddingTop: 10,
width: 110,
textAlign: "center",
marginLeft: 8,
marginRight: 15,
}}
>
<Typography noWrap variant="body2" gutterBottom>
{name}
</Typography>
</div>
{visible ? <Menu /> : null}
</div>
</div>
);
}
export default WebAppTypeCard;