Skip to content

Commit

Permalink
✨ - feat: restore autofocus when opening modal
Browse files Browse the repository at this point in the history
  • Loading branch information
svenvandescheur committed Aug 1, 2024
1 parent 340300c commit 1d4062a
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/components/modal/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type ModalProps = Omit<React.ComponentProps<"dialog">, "title"> & {
open?: React.ComponentProps<"dialog">["open"];
onClose?: React.ComponentProps<"dialog">["onClose"];
position?: "float" | "side";
restoreAutofocus?: boolean;
size?: "m" | "s";
title?: string | React.ReactNode;
};
Expand All @@ -27,6 +28,7 @@ export const Modal: React.FC<ModalProps> = ({
open,
onClose,
position = "float",
restoreAutofocus = true,
size,
title,
labelClose,
Expand All @@ -40,12 +42,26 @@ export const Modal: React.FC<ModalProps> = ({
if (open) {
dialogRef.current?.showModal();
setOpenState(true);
if (restoreAutofocus) {
doRestoreAutofocus();
}
} else {
setOpenState(false);
dialogRef.current?.close();
}
}, [open]);

/**
* Focuses the first child element with "autofocus" set.
*/
const doRestoreAutofocus = () => {
setTimeout(() => {
const input =
dialogRef.current?.querySelector<HTMLInputElement>("[autofocus]");
input?.focus();
});
};

/**
* Gets called when to modal is closed.
* @param e
Expand Down

0 comments on commit 1d4062a

Please sign in to comment.