티스토리 뷰

부모 컴포넌트에서 자식 컴포넌트의 state를 조작해야하는 상황이 생겼는데 나의 경우에는 ref를 여러개의 자식 컴포넌트에 달아서 조작하려고 했다. 그런데 ref는 current로만 접근할 수 있어서 마지막 하나의 자식 컴포넌트의 함수만 실행할 수 있었다. 한번에 여러개를 조작하려고 하시는 분은 참고하시길..!

 

부모 컴포넌트에서 자식 컴포넌트 state 조작하기

useRef를 사용해서 부모 컴포넌트에서 자식 컴포넌트를 조작할 수 있다. 

먼저 부모 컴포넌트에서 ref를 선언해서 자식 컴포넌트로 넘겨준다.

import { useRef } from 'react';
import Child from './Child';
import styled from 'styled-components';

const Parents = () => {
  const childRef = useRef();
  return (
    <Main>
      <h1>Manipulate</h1>
      <button className='btn'>
        reset
      </button>
      <Child ref={childRef} />
    </Main>
  );
};
export default Parents;

 

ref는 props로 넘겨줄 수 없기 때문에 자식 컴포넌트에서 forwardRef를 이용해서 받아줘야 한다.

// syntax
const 컴포넌트 = forwardRef((props, ref) => (<태그>));
import { useState, forwardRef } from 'react';

const Child = forwardRef((props, ref) => {
  const [count, setCount] = useState(1);
  return (
    <>
      <p className='count'>{count}</p>
      <button onClick={() => setCount((prev) => prev + 1)}>up</button>
    </>
  );
});

export default Child;

 

그리고 자식 컴포넌트에서 useImperativeHandle를 이용해서 받아온 ref에 부모 컴포넌트에서 사용할 함수를 넣어준다.

// syntanx
useImperativeHandle(ref, createHandle, [deps])
import { useState, forwardRef, useImperativeHandle } from 'react';

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    setCount,
  }));
  const [count, setCount] = useState(1);
  return (
    <>
      <p className='count'>{count}</p>
      <button onClick={() => setCount((prev) => prev + 1)}>up</button>
    </>
  );
});

export default Child;

 

부모 컴포넌트에서 ref를 찍어보면 useImperativeHandle를 이용해 넣은 함수를 확인할 수 있다.

부모 컴포넌트에서 childRef를 console에 찍었을 때

 

자식 컴포넌트의 함수를 실행시키고자 하는 곳에서 ref.current로 접근해 함수를 실행시키면 된다.

import { useRef } from 'react';
import Child from './Child';
import styled from 'styled-components';

const Parents = () => {
  const childRef = useRef();
  return (
    <Main>
      <h1>Manipulate</h1>
      <button className='btn' onClick={() => childRef.current.setCount(1)}>
        reset
      </button>
      <Child ref={childRef} />
    </Main>
  );
};
export default Parents;

 

이렇게 하면 부모 컴포넌트에서 자식 컴포넌트를 조작할 수 있다.

 

 

하지만 리액트 공식문서를 보면 되도록 ref를 이용한 명령형 코드는 피해야한다고 나와있다. 되도록 stats와 props를 이용하고 어쩔 수 없을 때 ref와 useImperativeHandle를 사용하면 될 것 같다.

728x90

'공부 노트' 카테고리의 다른 글

[Vite] Vite 프로젝트 gh-pages로 배포하기  (0) 2022.10.21
[Recoil] Recoil 시작하기  (0) 2022.10.06
[Git] git config 명령어  (0) 2022.09.27
[HTML] hidden 속성  (0) 2022.09.16
[Vite] Vite  (0) 2022.09.16
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
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
글 보관함