I'm developing a browser game in React. I have a grid of cells and I want that, when a cell is clicked, a dialog is opened right over it with some options.
Here is a rough visual of how it should be positioned when clicking on that cell, row 5, column 4:
I'm opened to use for the dialog any technique or library.
I tried to use the dialog in Headless UI - https://headlessui.com/react/dialog
I can only center it, or position it using fixed elements, like:
<Dialog className="absolute left-16 top-0 z-50">
The problem with this is that I would have to calculate them for every cell and, as the layout should be responsive, it would get complicated to calculate for different screen sizes.
Ideally I would have a dialog that opens relative to the cell (div) that was clicked.
Does anyone know how to do that, either with basic HTML + CSS, either with some React component library?
What you want can be easily achieved with the simple technique. You just need to get the position of box relative to the viewport using getBoundingClientRect
and apply the same position styles to the Modal dialog.
// This is called onClick
const showDialog = (e) => {
const rect = e.target.getBoundingClientRect();
// Calculate the top and left position dynamically
setModalStyles({
top: rect.top - 8,
left: rect.left - 38,
});
// Opne the modal
openDialog();
};
Here is a CodeSandbox demo.
And here is how it works:
One more option is to use PopOvers / Tooltips. These popovers appear just next to the element. So you just need to tweak little css to make them appear above the boxes.