TIL - 2022/05/20

유인종·2022년 5월 20일
0

React Component에서 'ref' 사용하기

  • parent 컴포넌트에서 다른 컴포넌트 내부에 있는 HTML 엘리먼트에 직접 접근해야할 때

  • refprop으로 넘겨줄 때 에러 발생

// ...
return (
  <Input ref={inputRef} />
)
// Warning: Input: `ref` is not a prop. Trying to access it will result in `undefined` being returned. 
// If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)
  • refprop이 아니라서 undefined가 설정될 것이다.

  • 그래서, 다른 prop을 사용해야한다.

    • ref 대신에 ref1처럼 다른 이름의 prop을 사용하면 해결할 수 있다.

    • 하지만, 위와 같은 해결법은 사용자 측면에서 컴포넌트 디자인을 혼란스럽게 받아들일 수 있다.


forwardRef

  • React에선 특수한 목적 때문에 prop으로 사용할 수 없는 것들이 존재

    • key, ref 등 ...
  • refprop으로 사용하기 위해 forwardRef() 함수 사용해야 한다.

  • Component를 forwardRef()로 감싸면 두 번째 매개변수를 갖게 되고, 이를 통해 외부에서 ref를 prop으로 넘겨줄 수 있다.

const Input = forwardRef((props, ref) => {
  return <input type="text" ref={ref} />;
});

  • TypeScript에서 사용
const Component = React.forwardRef<RefType, PropsType>((props, ref) => {
  return someComponent;
});
  • 예제
const App () => {
  const input = React.useRef<HTMLInputElement>(null);

  return <Search ref={input} />;
}

const Search = React.forwardRef<HTMLInputElement>((props, ref) => {
  return <input ref={ref} type="search" />;
});
  • forwardRef는 부모 컴포넌트가 자식 컴포넌트의 엘리먼트에 직접 접근하기 위해 사용한다.

  • 대신, 부모 컴포넌트가 어떤 엘리먼트 요소를 찾은 다음 해당 요소를 자식 컴포넌트에서 사용하기 위해 전달할 때는 보통의 stateprop처럼 사용한다.

// Child
const Child = ({someRef}) => {
  // ...
  someRef.current.scrollTo(0, 0) 
  // ...
}

// Parent
const divRef = useRef(null);

return (
  <div ref={divRef}/>  
  <Child someRef={ref} />
)



ref에 useState?

  • 작동은 하나, 렌더링이 두 번 된다.
    • 왜 이렇게 했을까..?
 const [rootTarget, setRootTarget] = useState<HTMLElement | null | undefined>(null)
// ...
retrun (
  <main className={styles.wrapper} ref={setRootTarget}>
  
  </main>
)



Ref Error

'MutableRefObject<HTMLElement | undefined>' 형식은 'LegacyRef<HTMLElement> | undefined' 형식에 할당할 수 없습니다.
  'MutableRefObject<HTMLElement | undefined>' 형식은 'RefObject<HTMLElement>' 형식에 할당할 수 없습니다.
    'current' 속성의 형식이 호환되지 않습니다.
      'HTMLElement | undefined' 형식은 'HTMLElement | null' 형식에 할당할 수 없습니다.
        'undefined' 형식은 'HTMLElement | null' 형식에 할당할 수 없습니다.
  • null로 초기화 해주기!
    • const ref = useRef<HTMLElement>(null)




참고

https://www.daleseo.com/react-forward-ref/
https://www.carlrippon.com/react-forwardref-typescript/
https://stackoverflow.com/questions/70683188/react-forwardref-property-current-does-not-exist-on-type-forwardedrefhtmlel

0개의 댓글