본문 바로가기
React를 같이 배워보자

React17일차-Portal,fowardRef

by 멈추지않아 2022. 2. 6.

오늘은 portal,forwardRef라는 API에 대해서 알아 보겠습니다.

우선 create-react-app으로 만들어주시고 코드 열어주세요

public/index.html로 이동 거시 바디 부분 <div id="root"></div> 밑에<div id="modal"></div> 추가해주세요

src/index.css로 이동해서

#modal {
  position: absolute;
  top: 0;
  left: 0;
}
 추가 해주세요

src/component/Modal.jsx 이렇게 폴더랑 파일 만들고

import ReactDOM from "react-dom";
const Modal = ({ children }) =>
  ReactDOM.createPortal(children, document.querySelector("#modal"));

export default Modal;
작성해주세요

이제 src/App.js로 이동해서

import "./App.css";
import { useState } from "react";
import Modal from "./component/Modal";

function App() {
  const [visible, setVisible] = useState(false);
  const open = () => {
    setVisible(true);
  };
  const close = () => {
    setVisible(false);
  };
  return (
    <div>
      <button onClick={open}>open</button>
      {visible && (
        <Modal>
          <div
            style={{
              width: "100vw",
              height: "100vh",

              background: "rgba(0,0,0,0.5)",
            }}
            onClick={close}
          >
            hello
          </div>
        </Modal>
      )}
    </div>
  );
}

export default App;

이러게  작성해주세요 그리고 npm  start해서 창을 보겠습니다.

클릭전
클릭후

이렇게 버튼을 클릭하면 위에 회색 배경으로 변하고 hello라고 있는 요소가 나옵니다. 다시 한번 클릭하면 원상태로 돌아가고를 visible이라는 state로 조절하고 있습니다. 

여기서 중요한것은 이부분 입니다.

이때까지는 root만 있언느데 지금 modal이 생겼고 다 root 안쪽으로 render됬는데 

이렇게 <Modal>내부에 있던 것들이 modal로 이동 되었습니다.  이게 바로 portal 의 기능입니다.

여기서 제공받은 children을 id가 modal인 곳으로 이동시킨것입니다. 

 

 

이제 forwardRef 에 대해서 알아봤습니다. 저번에 props의 이동은 우리가 해봤는데 ref의 이동은 안해봤습니다.

이번에는 ref의 이동을 해보겠습니다.

src/component/MyInput.jsx  만들고

import React from "react";
export default React.forwardRef(function MyInput(prop, ref) {
  return (
    <div>
      <p>내입력</p>
      <input ref={ref} />
    </div>
  );
});

작성

App.js에 가서

 

import "./App.css";
import { useRef } from "react";

import MyInput from "./component/MyInput";

function App() {
  const myInputRef = useRef();
  const click = () => {
    console.log(myInputRef.current.value);
  };
  return (
    <div>
      <MyInput ref={myInputRef}></MyInput>
      <button onClick={click}>send</button>
    </div>
  );
}

export default App;

작성

이코드는 즉 input요소에 작성하면 send클릭시  ref를 이용해서 찾아가서 그안에 내용을 콘솔에 찍어주는거다.

이걸 해주기 위해서는 MyInput에 myInputRef가 전달 되어야 되는데 이것은 바로 바로  forwardref로 이용해서 전달된것을 받을수 있다. 일단 제대로 동작되는지 확인해보겠다.

이렇게 npm start로 확인해본 결과 제대로 동작이된다. 그럼 fowardref의 기본 형식에 대해서  설명하겠다.

export default React.forwardRef(function 함수이름(props전달받을변수, ref를전달받을변수) {
  return 실행할html코드;
});

이런식이다 그래서 자기 입맛에 맞게 조절해서 쓰면 된다. 일요일임에도  다들 수고 가 많았습니다. ㅎㅎ 고생하셧어요