I have a React component like this
export const NewComponent: React.FC<NewComponentProps> = ({prop1, prop2, prop3 }) => {
const getAbsPositionDialog = () => {
const element = document.getElementById('modalDialogId');
if (!element) {
return { x: 0, y: 0 };
}
const dialogPosition = element.getBoundingClientRect();
return { x: dialogPosition.x, y: dialogPosition.y };
}
const dialogPosition = getAbsPositionDialog();
const horizontal = dialogPosition.x + 100;
const vertical = dialogPosition.y + 100;
const toasterId = useId("toaster");
const { dispatchToast } = useToastController(toasterId);
const notify = (title: string) => {
dispatchToast(
<Toast>
<ToastTitle>{title}</ToastTitle>
</Toast>,
{ intent: "success" }
);
}
React.useEffect(() => {
<Toaster
toasterId={toasterId}
position="top-start"
offset={{horizontal: horizontal, vertical: vertical}}
pauseOnHover
pauseOnWindowBlur
timeout={1000}
/>
}, [horizontal, vertical]);
return (
<div>
<Button onClick={notify("Copied!")}/>
</div>
);
};
The idea is to show a Toast component when clicking on the button. This NewComponent
is shown within a modal dialog and the location of the Toast notification is set at the top-start
relative to the whole window screen size, so it works well like that, showing the Toast notification at that position. No problem with it.
The problem comes when I try to add some offset based on the modalDialogId
. I want to know where the dialog is located so I can move the Toast notification closer to it, but when the component is executed, the modal dialog is not loaded yet and therefore the offset always returns as 0, 0
.
I tried to use the React.useEffect
to render the Toaster
which is where I set my offset later, but that didn't seem to work.
Is there a way to achieve this?