현재 모달이 열려있을 때, ESC 키로 닫을 수 없고, Tab 키로 모달 밖 요소에 포커스가 갈 수 있고, 모달이 열릴 때 포커스가 모달 안으로 이동하지 않습니다. 다음과 같이 수정할 수 있을 것 같습니다.
// src/components/common/Modal/index.tsx
const Root = ({ children, onClose }: RootProps) => {
const modalRef = useRef<HTMLDivElement>(null);
// ESC 키로 닫기
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [onClose]);
// 모달 열릴 때 포커스 이동
useEffect(() => {
const prevFocused = document.activeElement as HTMLElement;
modalRef.current?.focus();
return () => {
prevFocused?.focus(); // 닫힐 때 이전 포커스 복원
};
}, []);
return (
<ModalContext.Provider value={ { onClose } }>
<div
ref={modalRef}
tabIndex={-1}
className="fixed inset-0 flex items-center justify-center px-4 outline-none"
>
{children}
</div>
</ModalContext.Provider>
);
};
Originally posted by @DevelopSoo in #136