Home > Back-end >  Using forwardRef with React.FC component
Using forwardRef with React.FC component

Time:09-02

I am trying to use forwardRef with React.FC component in Typescript but Im getting the following TS error:

const Input: React.FC<InputProps>
Argument of type 'FC<InputProps>' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, InputProps>'.
  Types of property 'defaultProps' are incompatible.
    Type 'Partial<InputProps> | undefined' is not assignable to type 'undefined'.
      Type 'Partial<InputProps>' is not assignable to type 'undefined'.

Here is my code:

import React, { forwardRef } from 'react';
import style from './CustomInput.module.css';
interface InputProps {
    value: string;
    onChange: (value: string) => void;
    onClick: () => void;
}

const Input: React.FC<InputProps> = ({ value, onClick, onChange }, ref) => {
    return (
        <input
            className={style.CustomInput}
            type="text"
            value={value}
            ref={ref}
            onChange={e => onChange(e.target.value)}
            onClick={onClick}
        />
    );
};

export default forwardRef(Input);

I tried assinging extra props for refs like this: React.FC = ({ value, onClick, onChange }: InputProps, ref: HTMLInputElement)

But it doesnt seem to be solving the issue, any ideas how to fix this TS error?

CodePudding user response:

Don't use React.FC if you don't need it.

function Input({value, onClick, onChange}: InputProps, ref) {
  return (
    <input
      className={style.CustomInput}
      type="text"
      value={value}
      ref={ref}
      onChange={e => onChange(e.target.value)}
      onClick={onClick}
    />
  );
});


export default forwardRef(Input);
  • Related