Search code examples
reactjstypescriptreact-hooksreact-forwardref

Pass props when component use forwardRef typescript


I have an component AddComment with forwardRef:

function AddComment({ comment, setComment }: Props, ref: Ref<HTMLDivElement>) {
  return (<div ref={ref}>
  // code...
  </div>)
}
export default forwardRef<HTMLDivElement>(AddComment)

In parent component:

function Parent() {
  const [comment, setComment] = useState('')
  const addCommentRef = useRef<HTMLDivElement>(null)

  return (<div>
  // code ...
    <AddComment ref={addCommentRef} comment={comment} setComment={setComment}/>
  </div>)
}

I get this error:

Argument of type '({ comment, setComment }: Props, ref: Ref<HTMLDivElement>) => Element' is not assignable to parameter of type 'ForwardRefRenderFunction<HTMLDivElement, {}>'.
  Types of parameters '__0' and 'props' are incompatible.
    Type '{}' is missing the following properties from type 'Props': comment, setComment

When I run on browser, it runs well, but I have the error in VS Code.

How can I fix that?


Solution

  • forwardRef is a generic function that has type parameters for the type of the ref and the props.

    change it to forwardRef<HTMLDivElement, Props>(AddComment) to include Props type.

    read more on forwardRef in this article