parent 컴포넌트에서 다른 컴포넌트 내부에 있는 HTML 엘리먼트에 직접 접근해야할 때
ref
를 prop
으로 넘겨줄 때 에러 발생
// ...
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)
ref
는 prop
이 아니라서 undefined
가 설정될 것이다.
그래서, 다른 prop
을 사용해야한다.
ref
대신에 ref1
처럼 다른 이름의 prop
을 사용하면 해결할 수 있다.
하지만, 위와 같은 해결법은 사용자 측면에서 컴포넌트 디자인을 혼란스럽게 받아들일 수 있다.
React에선 특수한 목적 때문에 prop
으로 사용할 수 없는 것들이 존재
key
, ref
등 ...ref
를 prop
으로 사용하기 위해 forwardRef()
함수 사용해야 한다.
Component를 forwardRef()
로 감싸면 두 번째 매개변수를 갖게 되고, 이를 통해 외부에서 ref
를 prop으로 넘겨줄 수 있다.
const Input = forwardRef((props, ref) => {
return <input type="text" ref={ref} />;
});
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
는 부모 컴포넌트가 자식 컴포넌트의 엘리먼트에 직접 접근하기 위해 사용한다.
대신, 부모 컴포넌트가 어떤 엘리먼트 요소를 찾은 다음 해당 요소를 자식 컴포넌트에서 사용하기 위해 전달할 때는 보통의 state
와 prop
처럼 사용한다.
// Child
const Child = ({someRef}) => {
// ...
someRef.current.scrollTo(0, 0)
// ...
}
// Parent
const divRef = useRef(null);
return (
<div ref={divRef}/>
<Child someRef={ref} />
)
const [rootTarget, setRootTarget] = useState<HTMLElement | null | undefined>(null)
// ...
retrun (
<main className={styles.wrapper} ref={setRootTarget}>
</main>
)
'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