I am working on a project using React Native with Typescript. I am trying to forwardRef to my Pressable component but I keep getting an error that states:
Blockquote 'Pressable' refers to a value, but is being used as a type here. Did you mean 'typeof Pressable'?
I also decided to use the "typeof Pressable" and the error was gone but the ref passed to the rendered Pressable component throw a new error below:
Blockquote Types of parameters 'instance' and 'instance' are incompatible. Type 'View | null' is not assignable to type 'ForwardRefExoticComponent<PressableProps & RefAttributes> | null'.
I have reproduced the code below:
const Item = React.forwardRef<Pressable, ItemProps>((props, ref) => {
return (
<Pressable ref={ref}>
<Text>Item 1</Text>
</Pressable>
)
})
How can I get rid of this error and have the ref type properly mapped to the Pressable component?
The issue is that Pressable itself also forwards its ref (to View). This can be seen from its type: React.ForwardRefExoticComponent<PressableProps & React.RefAttributes<View>>. A simple way to see what's going on is to pass a dummy {} as any ref to Pressable and hover over ref:
const test = <Pressable ref={{} as any}/>
// (property) RefAttributes<View>.ref?: React.Ref<View> | undefined
This shows that Pressable expects ref to have type Ref<View> instead of a Ref<Pressable>, which can be achieved by passing View as the first type parameter to forwardRef:
type ItemProps = {label: string}
const Item = React.forwardRef<View, ItemProps>(
(props, ref) =>
<Pressable ref={ref}>
<div>Item 1: {props.label}</div>
</Pressable>
)
const Test = () => {
const ref = React.createRef<View>();
return <Item label='Test' ref={ref}/>
}
TypeScript playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With