How to infer the ref type of a component?

Let's say you have a component that wraps an input:
const Input = React.forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<"input">>((props, ref) => {
return <input ref={ref} type="text" />;
});
const Input = React.forwardRef<HTMLInputElement, React.ComponentPropsWithoutRef<"input">>((props, ref) => {
return <input ref={ref} type="text" />;
});
And another component using Input, and forwarding the ref to it:
const LabelInput = React.forwardRef<HTMLInputElement, LabelInputProps>(({ text, ...props }, ref) => {
return (
<div>
<label>{text}</label>
<Input ref={ref} {...props} />
</div>
);
}
);
const LabelInput = React.forwardRef<HTMLInputElement, LabelInputProps>(({ text, ...props }, ref) => {
return (
<div>
<label>{text}</label>
<Input ref={ref} {...props} />
</div>
);
}
);
Here, we give HTMLInputElement as first type param of React.forwardRef. Is there a way to compute this value dynamically? In other words, is there a way to introspect the type of ref of Input? https://codesandbox.io/s/keen-swanson-rcxint?file=/src/App.tsx
brmzkw
CodeSandbox
keen-swanson-rcxint - CodeSandbox
keen-swanson-rcxint by brmzkw using react, react-dom, react-scripts
1 Reply
Julien Castets
Julien CastetsOP3y ago
I tried React.ComponentPropsWithRef<typeof Input>["ref"] but it doesn't work, I'm not sure it even makes sense. wooouhh, actually I can
const LabelInput = React.forwardRef(({ text, ...props }: LabelInputProps, ref: React.ComponentPropsWithRef<typeof Input>["ref"]) => {
const LabelInput = React.forwardRef(({ text, ...props }: LabelInputProps, ref: React.ComponentPropsWithRef<typeof Input>["ref"]) => {
it seems to work to put the type here.
Want results from more Discord servers?
Add your server