[React] Modal

DongHyeon Jung·2022년 10월 3일
0

React

목록 보기
10/15
post-thumbnail

Modal

아래의 코드가 좋지 않은 이유는 무엇일까?

modal은 페이지 전체를 덮어야 한다
모든 것들 위에 있어야 하므로 좋은 구조는 아니다

처음에 기준이 되는 엘리먼트를 지정해야 한다
ReactModal.setAppElement('#root');

<div id="overlays"></div>

이렇게 지정해준다

const portalsElement = document.getElementById('overlays');
const Modal = props => {
<Fragment>
	{ReactDOM.createPortal(<Backdrop />, portalsElement)}
	{ReactDOM.createPortal(<ModalOverlay>{props.children}</ModalOverlay>)}
</Fragment>;
};

Modal이란?

어떠한 형식(mode)으로 된 화면을 의미하며 쉽게 이해하려면 Dialog나 팝업 창을 띄우는 화면

Modal을 사용하는 이유?

The main advantage of modals is that they are independent of the active page, meaning they can be used to add, update, delete, or view the information, they are easy to open and close, they do not require changing the current URL, and the background information is often fully or partially visible.

[ebay_nice-modal] : https://github.com/eBay/nice-modal-react

function App() {
const [openModal, setOpenModal] = useState(false);

const openModalHandler = () => {
	setOpenModal(true);
};

return (
	<div className="App">
	<h1>Click modal button</h1>
	<div className="buttons d-grid gap-2">
		<Button
		variant="primary"
		className="modalBtn"
		size="lg"
		onClick={openModalHandler}
>			
		Modal
		</Button>
	</div>
	{openModal && <Modal closeModal={setOpenModal} />}
	</div>
);
}
  
export default App;

openModal이라는 state를 만들어서 버튼을 클릭할때 모달이 false -> true로 바뀌게 한다
Modal component로 props를 전달해서 모달창에서도 조작이 가능하게 한다

📚 예제코드
https://github.com/jdh4601/react_modal.git

0개의 댓글