A ref on a native component returns an element node, an object modelled on the web's Element with getBoundingClientRect(), offsetWidth, textContent and tree traversal. That gives you layout reads and imperative calls such as focus() through APIs you already know from the DOM. The tree is read-only, though, and only components backed by a native view hand out nodes, so your own components have to pass refs along.

Key terms

  • Element node: the object a native component's ref returns, representing that component in the native view tree the way an Element represents a tag on the web.
  • Host component: a component backed by a native view, such as View, Text or TextInput, and the only kind whose ref gives you an element node.
  • Composite component: a component that is not directly backed by a native view, which covers most components you write yourself.
  • ViewInstance: the type react-native exports for a View ref, defined as HostInstance, which is in turn an alias of ReactNativeElement.
  • Document node: the node for a complete native view tree, which you can only reach from another node, for example through ownerDocument.

Three kinds of node

React Native gives imperative access to its native view tree through refs. Every native component returns one, including the native components that built-in components such as View render. The tree holds three kinds of node. Element nodes stand for native components. Text nodes hold raw text content, and a ref never returns one directly: you reach them from an element through properties such as childNodes. A document node represents a whole native view tree.

Apps that use native navigation get a separate document per screen, while apps without it usually have one document for the whole app. From any element, ownerDocument gives you that document and getElementById() finds another element in it by id. In TypeScript both can be null, and getElementById() is typed to return a ReadOnlyElement, which declares no focus(). The docs call focus() on the result in plain JavaScript, but in a typed file you cast it first, for example to TextInputInstance: const input = card.ownerDocument?.getElementById('main-text-input') as TextInputInstance | null; and then input?.focus();.

Two properties help when you log nodes while debugging. tagName returns the native component name with an RN: prefix, such as RN:View. id returns the id prop, falls back to nativeID, and is an empty string when neither is a string.

Layout through the web API

Element nodes implement the layout properties of HTMLElement: offsetWidth, offsetHeight, offsetTop, offsetLeft and offsetParent, next to getBoundingClientRect(). The two size readings differ. getBoundingClientRect() always includes transforms, while offsetWidth and offsetHeight come from the same rectangle with transforms left out, rounded with Math.round. A view with a scale transform reports different sizes through the two APIs.

Type refs with the component-specific instance types that react-native exports, such as ViewInstance and TextInputInstance, imported with import type. View's ref prop is typed React.Ref<ViewInstance>, so useRef<ViewInstance>(null) fits it without a cast.

The ProfileScreen example below the lesson reads the card's node in a useLayoutEffect once the screen has mounted. Two lines do the work:

tsx
const rect = card.getBoundingClientRect();
setSummary(`${card.tagName}: ${card.offsetWidth} x ${card.offsetHeight}, y ${rect.y}`);

The tagName in that summary is RN:View, because the node behind the card is the View that ProfileCard renders.

Read, never write

Nodes can't be mutated the way DOM nodes can. There is no appendChild, because the React renderer fully manages the tree. You can't create a node either: the public HTMLElement constructor throws a TypeError saying nodes cannot be imperatively created in React Native. Adding, removing or reordering views still goes through rendering.

Some built-in components wrap more than one native component. ScrollView renders a native scroll view and a native view inside it, and its ref reaches them through getNativeScrollRef() and getInnerViewRef(). getNativeScrollRef() returns null when the scroll view isn't mounted. Among built-in components, only a ScrollView instance can report a scrollTop or scrollLeft other than zero.

Refs on your own components

Only host components give you a HostInstance. A composite component, which includes most of your own, exposes none unless it passes the ref on to a host component. Put a ref on <ProfileCard> and you get no element node until ProfileCard hands that ref to a View.

ProfileCard does it by reading props.ref and putting it on the View it renders:

tsx
<View ref={props.ref} style={styles.card}>

Calls on the card's ref then act on that View. This works because ProfileCard is a plain function component: the React renderer bundled with React Native passes a function component its props with ref still in them. A forwardRef component or a class component gets its props with ref removed, so neither can read props.ref. React Native's own ScrollView export uses the props pattern, a function component that takes ref from its props without forwardRef. With forwardRef, you forward the ref to one of the View components the custom component renders instead. Either way, you decide which View the caller gets. If callers will measure the whole card, give them the outermost one.

Code Examples

tsx
import {useLayoutEffect, useRef, useState} from 'react';
import type {ReactNode, Ref} from 'react';
import {StyleSheet, Text, View} from 'react-native';
import type {ViewInstance} from 'react-native';

type ProfileCardProps = {
  ref?: Ref<ViewInstance>;
  children: ReactNode;
};

function ProfileCard(props: ProfileCardProps) {
  // Hand the ref to a host component so callers get its element node
  return (
    <View ref={props.ref} style={styles.card}>
      {props.children}
    </View>
  );
}

export function ProfileScreen() {
  const cardRef = useRef<ViewInstance>(null);
  const [summary, setSummary] = useState('');

  useLayoutEffect(() => {
    const card = cardRef.current;
    if (card == null) {
      return;
    }
    const rect = card.getBoundingClientRect();
    setSummary(`${card.tagName}: ${card.offsetWidth} x ${card.offsetHeight}, y ${rect.y}`);
  }, []);

  return (
    <View>
      <ProfileCard ref={cardRef}>
        <Text>Grace Hopper</Text>
        <Text>Compiler engineer</Text>
      </ProfileCard>
      <Text>{summary}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  card: {padding: 16, borderRadius: 12, backgroundColor: '#eef2ff'},
});
✓ Completed