HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
🗂️
React, Hook 들어오네!?
/
😊
회의록
/
🪞
useImperativeHandle
/
9.3.1 useImperativeHandle을 사용하지 않은 실용예제

9.3.1 useImperativeHandle을 사용하지 않은 실용예제

예제 설명

자식 컴포넌트의 태그 요소들을 부모 컴포넌트에서 제어하기위한 예제를 작성하였습니다.
모달창 안에 있는 각각의 상자들을 모달창 외부에서 버튼을 통해 색상을 넣어주는 예제입니다.
 
그림 9-1
그림 9-1

useImperativeHandle을 사용하지 않은 예제

 
// App.jsx import { useState } from "react"; import CustomModal from "./CustomModal"; function App() { const [open, setOpen] = useState(false); const [isTomato, setIsTomdato] = useState(false); const [isPink, setIsPink] = useState(false); const [isSky, setIsSky] = useState(false); return ( <> <button onClick={() => setOpen(true)}>Open</button> <button onClick={() => { setIsPink(true); }} > Pink Btn </button> <button onClick={() => { setIsSky(true); }} > Skyblue Btn </button> <button onClick={() => { setIsTomdato(true); }} > Tomato Btn </button> <CustomModal isOpen={open} onClose={() => { setOpen(false); setIsPink(false); setIsSky(false); setIsTomdato(false); }} isPink={isPink} isSky={isSky} isTomato={isTomato} /> </> ); } export default App;
App.jsx
자식 컴포넌트의 DOM에 직접 접근이 불가능하니, 상태값을 생성하여 자식 컴포넌트에 props 값으로 넘겨줍니다.
각 div 태그의 색상을 결정하기 위한 세개의 상태값, 모달창을 여닫을 하나의 상태값을 생성하여 전달합니다.
 
// CustomModal.jsx import React, { useRef } from "react"; import { useEffect } from "react"; const CustomModal = ({ isOpen, onClose, isPink, isSky, isTomato }) => { const closeRef = useRef(); const pinkRef = useRef(); const skyblueRef = useRef(); const tomatoRef = useRef(); useEffect(() => { if (isPink) { pinkRef.current.style = "width:50px; height:50px; background:pink;"; } if (isSky) { skyblueRef.current.style = "width:50px; height:50px; background:skyblue;"; } if (isTomato) { tomatoRef.current.style = "width:50px; height:50px; background:tomato;"; } }, [isPink, isSky, isTomato]); if (!isOpen) return null; return ( <div> <br /> <button ref={closeRef} onClick={onClose}> &times; </button> <h1>Color Change</h1> <div> <div ref={pinkRef}>color1</div> <div ref={skyblueRef}>color2</div> <div ref={tomatoRef}>color3</div> </div> </div> ); }; export default CustomModal;
CustomModal.jsx
CustomModal 컴포넌트에서는 각 div태그에 접근하기 위한 Ref를 생성해줍니다.
props로 넘겨받은 각 상태값이 true로 바뀔 경우, Ref를 통해 해당 DOM에 접근하여 스타일을 바꿔줍니다.
 
위 코드는 부모컴포넌트에서 useState를 내려주어 자식컴포넌트 안에서 특정 태그에 영향을 주는 방법입니다. 하지만 다음에 나올 예제처럼 useImperativeHandle을 사용한다면, 부모에서 직접 자식컴포넌트의 태그에 접근할 수 있습니다.