It’s my first attempt with React TypeScript and don’t fully understand the error I’m getting when trying to build a reusable Input component. What is the TypeScript way of approaching this kind of component?
See Component & Error below:
JavaScript
x
25
25
1
import React, { FC, InputHTMLAttributes } from 'react';
2
3
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
4
name: string;
5
label: string;
6
ref: string;
7
}
8
9
const Input: FC<InputProps> = ({ name, label, otherProps }, ref) => {
10
return (
11
<label className={styles.formLabel}>
12
{label}
13
<input
14
className={styles.formInput}
15
{otherProps}
16
name={name}
17
ref={ref}
18
/>
19
</label>
20
);
21
};
22
23
const FormInput = React.forwardRef(Input);
24
25
export default FormInput;
Error
JavaScript
1
13
13
1
TypeScript error in /Users/Timmchoover/Documents/Projects/evaly/evaly-app/src/before-login/components/forms/form-input/form-input.component.tsx(25,36):
2
Argument of type 'FC<InputProps>' is not assignable to parameter of type 'ForwardRefRenderFunction<unknown, InputProps>'.
3
Types of property 'defaultProps' are incompatible.
4
Type 'Partial<InputProps> | undefined' is not assignable to type 'undefined'.
5
Type 'Partial<InputProps>' is not assignable to type 'undefined'. TS2345
6
7
23 | };
8
24 |
9
> 25 | const FormInput = React.forwardRef(Input);
10
| ^
11
26 |
12
27 | export default FormInput;
13
28 |
Advertisement
Answer
I don’t think FC
is satisfying the type constraint here, try ForwardRefRenderFunction
instead:
JavaScript
1
26
26
1
import React, { ForwardRefRenderFunction, InputHTMLAttributes } from 'react';
2
3
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
4
name: string;
5
label: string;
6
ref: string;
7
}
8
9
const Input: ForwardRefRenderFunction<HTMLInputElement, InputProps> = ({ name, label, otherProps }, ref) => {
10
return (
11
<label className={styles.formLabel}>
12
{label}
13
<input
14
className={styles.formInput}
15
{otherProps}
16
name={name}
17
ref={ref}
18
/>
19
</label>
20
);
21
};
22
23
const FormInput = React.forwardRef(Input);
24
25
export default FormInput;
26
Alternatively, you can combine Input
and FormInput
into one and let TypeScript infer for you:
JavaScript
1
7
1
const FormInput = React.forwardRef<HTMLInputElement, InputProps>(({ name, label, otherProps }, ref) => {
2
3
});
4
5
6
export default FormInput;
7