단순 코드 기록/React

React_자식창을 모달창으로 불러오기

일일일코_장민기 2024. 3. 18. 10:11
728x90
App
import { useRef} from "react"
import Box from "./components/box"

export default function App(){

  const boxRef = useRef();

  function handleEvent(){
    console.log("부모창에서 자식창의 open함수 호출")
    boxRef.current.open();    //자식의 open함수 호출
  }

  return (
    <>
    <h1>App</h1>
      <button onClick={handleEvent}>자식의 open 호출</button>
      <Box ref={boxRef}>모달창 보기</Box>
    </>
  )
}

 

box
import { useRef, useImperativeHandle, forwardRef } from "react"

//반드시 fowardRef로 감싸고 Ref로 받음
const Box = forwardRef((props, ref) => {
    const modal = useRef();
    useImperativeHandle(ref, () => ({open})); //부모에게 노출
 
    function open(){                          //부모가 호출할 함수
      modal.current.showModal();              //모달창 띄우기
    }
 
    const handleClose = () => {
      modal.current.close();
    };
 
    return(
      <>
        <dialog ref={modal}>                  {/* 모달창 시작 */}
          <h2>모달창</h2>
            <form>
              아이디: <input></input>
              비밀번호: <input></input>
              <button onClick={handleClose}>저장</button>
            </form>
        </dialog>                              {/* 모달창 끝 */}
      </>
    )
  })//forwardRef

  export default Box;