내일배움캠프

230814 react 모달이 열릴 때 포커스를 주고 닫을 때 원래대로 돌려주기

Neda 2023. 8. 14. 23:33

230814 react 모달이 열릴 때 포커스를 주고 닫을 때 원래대로 돌려주기

 

모달을 열 때

  1. 현재 포커스 중인 엘리먼트를 저장
  2. 모달 컴포넌트로 포커스를 이동
const modalRef = useRef<HTMLDivElement | null>(null);
const previousFocusRef = useRef<HTMLElement | null>(null);
  useEffect(() => {
    const focusedElementBeforeModal = document.activeElement as HTMLElement;
    previousFocusRef.current = focusedElementBeforeModal;
    if (modalRef.current) {
      modalRef.current.focus();
    }
  }, []);
  
  return(
  <ModalWrapper {...props} ref={modalRef} tabIndex={-1}>
        {children}
  </ModalWrapper>
  )

 

모달을 닫을 때

  1. useEffeact의 return 함수에서 저장해 둔 기존의 포커스 요소로 포커스를 이동
    return () => {
      if (previousFocusRef.current) {
        previousFocusRef.current.focus();
      }
    };

'내일배움캠프' 카테고리의 다른 글

230817 CPU와 메모리  (0) 2023.08.17
230816 supabase data types and range  (0) 2023.08.16
230814 KPT 회고  (0) 2023.08.14
230813 내일배움캠프 13주차 WIL  (0) 2023.08.13
230812 ant design을 쓰면서 느낀 점  (0) 2023.08.12