Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle refs for Pressable in React Native

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?

like image 423
Hamed Jimoh Avatar asked Oct 24 '25 16:10

Hamed Jimoh


1 Answers

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

like image 139
Oblosys Avatar answered Oct 27 '25 05:10

Oblosys