Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

죽이죽이

React : Portal 본문

React

React : Portal

죽이죽이 2024. 2. 19. 13:02

Portal

※ Portal이란?
- DOM의 일부 자식 컴포넌트를 DOM의 다른 부분으로 렌더링 할 수 있게 해주는 기능이다.


※ Portal을 사용하는 이유
- 대표적으로 modal 같은 경우는 전체 컴포넌트에 뒤덮힐 수 있는 요소이기 때문에 최상위 요소(html, body) 하위에 있어야 한다.
- 또한 부모 컴포넌트의 스타일링의 영향을 받게 되기때문에 별도의 번거로운 후처리를 해주어야 한다.
- 이를 Portal을 사용하여 부모-자식 관계를 유지하면서 독립적으로 원하는 위치에서 동작을 할 수 있게 해준다.


※ 사용 방법


※ 예시
- index.html

  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="backdrop-root"></div> // 모달을 렌더링해줄 새로운 html 요소 생성
    <div id="overlay-root"></div> // 모달을 렌더링해줄 새로운 html 요소 생성
    <div id="root"></div>
  </body>


- Dice.jsx

{ReactDOM.createPortal(
	<Backdrop player={player} />, // 상태값 전달 가능
	document.getElementById("backdrop-root")
)}

{ReactDOM.createPortal(
	<ModalOverlay player={player} />, // 상태값 전달 가능
	document.getElementById("overlay-root")
)}

 

// 배경
const Backdrop = ({ player }) => {
  return player.some((e) => e.isWinner) && <div className={styles.backdrop}></div>;
};

// 모달 창
const ModalOverlay = ({ player }) => {
  const playerSort = JSON.parse(JSON.stringify(player)).sort((a, b) => b.totalScore - a.totalScore);
  return (
    playerSort.some((e) => e.isWinner) && (
      <ol className={styles.modal}>
        {playerSort.map((e) => (
          <li>
            {e.playerName} / {e.totalScore}
          </li>
        ))}
      </ol>
    )
  );
};


- 결과

 

'React' 카테고리의 다른 글

React : Custom Hook  (0) 2024.02.23
React : debounce  (0) 2024.02.20
React : key props가 필요한 이유  (0) 2024.02.13
React : 이미지 처리  (0) 2024.02.13
React : Form 데이터 조작 방법  (0) 2024.02.12