Refactor: Portal 컴포넌트 리팩토링
se030 opened this issue · comments
♻️ 리팩토링 사항
전체 컴포넌트가 하나의 portal root div를 공유하게되는 문제가 있습니다.
현재 Toast 컴포넌트에서만 사용하고 있었지만 Modal, Drawer 등의 컴포넌트도 쌓임 맥락 외부에 위치해야 하므로 Portal 사용이 필요합니다.
-
고정된 root를 사용하고 있는 Portal 컴포넌트에 rootId props를 추가합니다.
Toast 컴포넌트도 작업 중이므로 기존 동작은 건드리지 않고 타 컴포넌트도 사용할 수 있도록 수정합니다. 추후 Toast에도 반영이 필요합니다.
📖 참고 사항
작업하려고 봤더니 이미 이렇게 되어있네요 😅
나중에 id 필수 props로 변경하고 Toast 쪽만 수정하면 될 것 같습니다!
import { PORTAL_ROOT_ID } from '@constants/portal';
import { ReactNode, useEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
interface PortalProps {
id?: string;
children: ReactNode;
}
const Portal = ({ id, children }: PortalProps) => {
const ref = useRef<Element | null>();
const [mounted, setMounted] = useState<boolean>(false);
useEffect(() => {
setMounted(true);
const portalRoot = document.getElementById(id ?? PORTAL_ROOT_ID);
ref.current = portalRoot;
}, []);
if (ref.current && mounted) {
return createPortal(children, ref.current);
}
return null;
};
export default Portal;