[TIL] react PORTAL!

Keunyeong Lee·2022년 5월 5일
0

[TIL]

목록 보기
3/15
post-thumbnail

신세계

놀라운건 넘쳐난다.

모달을 구현하기 위해 강사님께 추천받은 React Portal을 알아보자.

React Portal

https://ko.reactjs.org/docs/portals.html

공식 문서 읽어주고!

portal은 DOM 트리의 어디에나 존재할 수 있고 일반적인 React 자식처럼 동작한다.

<html>
  <body>
    <div id="app-root"></div>
    <div id="modal-root"></div>
  </body>
</html>

app-root 위에 modal-root 를 띄워버려!!!!

// portal.jsx
const ModalPortal = ({ children }) => {
  const el = document.getElementById("modal");
  return reactDom.createPortal(children, el);
};
export default ModalPortal;

이런식으로 준비를 하고

//Modal.js

import React from "react";
import ModalPortal from "./Portal";
import styled from "styled-components";

const Modal = ({ onClose}) => {

  return (
    <ModalPortal>
      <Background>
        <Content>
         </ Content>
      </Background>
    </ModalPortal>
  );
};

export default Modal;

이걸 띄우는 거!

띄울 위치에

{isModal && <Modal onClose={handleModal} />}

이런 형태로 사용하면 된다.

isModal 을 state 로 true/false 로 열었다 닫았다 하게 하면 끝!

여기서 애니메이션을 고민했는데

setTimeout 을 걸어서 열리고 0.01초 후 className 변경해서 애니메이션 주기!

종료는 false 바꾸기 위해 버튼을 누르면 className 먼저 바꾸고 1초 혹은 애니메이션 설정된 시간이 흐른 후에 false로 바꿔 모달이 꺼지도록 해보았다.

애니메이션 처리 방식이 올바른지는 모르겠지만 모달을 아주 간편하게 사용할 수 있게 된것 같음!!

놀라운 리엑트..

profile
🏃🏽 동적인 개발자

0개의 댓글