How to type React Native ref in TypeScript


This post goes over how to type React Native ref in TypeScript.

Prerequisites

Assuming you have React and TextInput imported:

import React from 'react';
import { TextInput } from 'react-native';

useRef

Use the React.useRef hook for function components:

const ref = React.useRef<TextInput>();

This is the same as:

let ref: React.RefObject<TextInput> | null = null;
ref = React.useRef(null);

createRef

Use React.createRef for class components:

const ref = React.createRef<TextInput>();

This is the same as:

let ref: React.RefObject<TextInput> | null = null;
ref = React.createRef();

ElementRef

Use ElementRef for ref callback:

let ref: React.ElementRef<typeof TextInput> | null = null;
<TextInput ref={(element: TextInput) => (ref = element)} />;

This is the same as:

let ref: React.ElementRef<typeof TextInput> | null = null;
const callback: React.RefCallback<TextInput> = (element: TextInput) =>
  (ref = element);
<TextInput ref={callback} />;

As well as:

let ref: React.ElementRef<typeof TextInput> | null = null;
const callback: React.LegacyCallback<TextInput> = (element: TextInput) =>
  (ref = element);
<TextInput ref={callback} />;


Please support this site and join our Discord!