티스토리 뷰
반응형
실무에서 모든 JS파일이 Typescript로 마이그레이션 된 상태는 아닌데
이 와중에 forwardRef를 사용하는 JS 컴포넌트와 부모 TSX컴포넌트 사이에서 타입에러가 발생하였다.
JSDoc을 사용하여 자식 JS파일에 적용하여 타입에러를 해결했는데 이를 정리해본다.

부모 컴포넌트에서 정의한 Ref를 자식 컴포넌트로 전달할 때 사용하는 기능
import React, { forwardRef, useEffect } from 'react';
const ChildComponent = forwardRef((props, ref) => {
useEffect(() => {
if (ref.current) {
ref.current.focus();
}
}, [ref]);
return (
<input type="text" ref={ref} />
);
});
const ParentComponent = () => {
const inputRef = React.createRef();
return (
<div>
<ChildComponent ref={inputRef} />
</div>
);
};
2개의 파라미터를 가지며 하나는 자식 컴포넌트가 받는 Props, 하나는 자식 컴포넌트에게 전달할 Ref 이다.
JS와 TSX를 혼용하고 있다면(내 상황처럼 마이그레이션 중이라면) 아래와 같은 JSDoc 구문을 이용해야 eslint의 타입 에러를 막을 수 있다.
import React, { forwardRef, useEffect } from 'react';
/**
* @typedef {Object} ChildComponentProps
* @property {string} sampleParam
*/
/**
* * @type {React.ForwardRefExoticComponent<ChildComponentProps & React.RefAttributes<any>>}
*/
const ChildComponent = forwardRef(({sampleParam}, ref) => {
useEffect(() => {
if (ref.current) {
ref.current.focus();
}
}, [ref]);
return (
<input type="text" ref={ref} />
);
});
반응형
'React와 NextJS' 카테고리의 다른 글
Link태그와 a태그의 차이 (0) | 2024.11.26 |
---|---|
Textarea에 폰트 추가 기능을 넣어보자 (0) | 2024.11.23 |
getElementBy보다 useRef를 사용해야하는 이유 (0) | 2024.11.16 |
Fragment란? (0) | 2024.11.14 |
MongoDB with NextJS (0) | 2024.11.11 |
- Total
- Today
- Yesterday
반응형