interface Props {
visible?: Boolean;
}
const ModalBox = styled.div<Props>`
<...>
display: ${(props) => props.visible ? 'flex' : 'none'};
z-index: 150;
<...>
`;
const Modal = (props: any) => {
const [isBrowser, setIsBrowser] = useState(false);
useEffect(() => {
setIsBrowser(true);
}, []);
const [show, setShow] = useState(false);
const CloseHandler = () => {
setShow(false);
props.onClose(false);
};
useEffect(() => {
setShow(props.show);
}, [props.show]);
if (isBrowser) {
return ReactDOM.createPortal(
<ModalBox visible={show}>
<span onClick={CloseHandler}>←</span>
<div>
<div>{props.title}</div>
<div>{props.children}</div>
</div>
</ModalBox>,
document.getElementById("modal-root")
);
} else {
return null;
}
};
export default Modal;
<...>
<div id='modal-root'></div>
<Header />
<Mainbody>
<Component {...pageProps} />
</Mainbody>
<...>
const Test = React.memo(() => {
<...>
const [isVisible, setIsVisible] = useState(false);
const onSetIsVisible = () => {
setIsVisible(isVisible => !isVisible);
};
return (
<>
<Modal
onClose={onSetIsVisible}
show={isVisible}
title='title'>
<div>{children}</div>
</Modal>
<Button onClick={onSetIsVisible}>버튼</Button>
}
<...>
- getElementById의 정확한 사용법
- React.DOM의 사용법