본문 바로가기
프로그래밍/React

[React] forwardRef

by YuminK 2023. 11. 29.

forwardRef

forwardRef lets your component expose a DOM node to parent component with a ref.

 

const SomeComponent = forwardRef(render)

 

Parameters 

render: The render function for your component. React calls this function with the props and ref that your component received from its parent. The JSX you return will be the output of your component.

 

Returns 

forwardRef returns a React component that you can render in JSX. Unlike React components defined as plain functions, a component returned by forwardRef is also able to receive a ref prop.

 

render function 

forwardRef accepts a render function as an argument. React calls this function with props and ref:

 

const MyInput = forwardRef(function MyInput(props, ref) {

  return (

    <label>

      {props.label}

      <input ref={ref} />

    </label>

  );

});

 

Parameters 

props: The props passed by the parent component.

 

ref:  The ref attribute passed by the parent component. The ref can be an object or a function. If the parent component has not passed a ref, it will be null. You should either pass the ref you receive to another component, or pass it to useImperativeHandle.

 

Returns 

forwardRef returns a React component that you can render in JSX. Unlike React components defined as plain functions, the component returned by forwardRef is able to take a ref prop.

 

forwardRef를 사용하여 컴포넌트를 감싸고, 내부 DOM객체에 ref로 넘겨라.  

 

import { forwardRef } from 'react';

 

const MyInput = forwardRef(function MyInput(props, ref) {

  const { label, ...otherProps } = props;

  return (

    <label>

      {label}

      <input {...otherProps} ref={ref} />

    </label>

  );

});

 

이를 통해, 부모 컴포넌트에서 다음과 같이 사용할 수 있다. 

 

function Form() {

  const ref = useRef(null);

 

  function handleClick() {

    ref.current.focus();

  }

 

  return (

    <form>

      <MyInput label="Enter your name:" ref={ref} />

      <button type="button" onClick={handleClick}>

        Edit

      </button>

    </form>

  );

}

 

ref를 DOM 노드에 노출하는 것은 컴포넌트의 내부 변경을 어렵게 만든다는 것을 인지해라. forwardRef를 중첩으로 ref를 내려줄 수 있는데, imperative handle을 정의하여 따로 만들 수 있다. DOM 노드를 직접 보여주지 않고, custom 오브젝트를 반환할 수 있다. 

 

import { useRef } from 'react';

import MyInput from './MyInput.js';

 

export default function Form() {

  const ref = useRef(null);

 

  function handleClick() {

    ref.current.focus();

    // This won't work because the DOM node isn't exposed:

    // ref.current.style.opacity = 0.5;

  }

 

  return (

    <form>

      <MyInput placeholder="Enter your name" ref={ref} />

      <button type="button" onClick={handleClick}>

        Edit

      </button>

    </form>

  );

}

 

import { forwardRef, useRef, useImperativeHandle } from 'react';

 

const MyInput = forwardRef(function MyInput(props, ref) {

  const inputRef = useRef(null);

 

  useImperativeHandle(ref, () => {

    return {

      focus() {

        inputRef.current.focus();

      },

      scrollIntoView() {

        inputRef.current.scrollIntoView();

      },

    };

  }, []);

 

  return <input {...props} ref={inputRef} />;

});

 

export default MyInput;

 

props로 처리할 수 없는 부분에 대해서만 imperative handle로 처리하는 것이 낫다고 한다. 

 

https://react.dev/reference/react/forwardRef

'프로그래밍 > React' 카테고리의 다른 글

[React] createContext  (0) 2023.11.29
[React] useContext  (0) 2023.11.29
[React] memo  (1) 2023.11.29
[React] useMemo  (0) 2023.11.29
[React] useCallback  (1) 2023.11.28

댓글