Ref Functions
React allows you to grab the instance of an element or component with refs.
Refs in Functional Components
Inside a component, refs are accessed with the useRef hook:
1import {useRef} from 'react';2import * as React from 'react';3
4component MyComponent() {5 const buttonRef = useRef<null | HTMLButtonElement>(null);6 buttonRef as {current: null | HTMLButtonElement}; // useRef wraps the ref value in an object7 return <button ref={buttonRef}>Toggle</button>;8}Note that useRef wraps the ref value in an object with a current property. This must be
reflected in the type of anything accepting the ref value.
Refs in Class Components
Refs in class components are similar to function components. To create one, add a
property to your class and assign the result of React.createRef to it.
1import * as React from 'react';2
3class MyComponent extends React.Component<{}> {4 // The `null` here is important because you may not always have the instance.5 buttonRef: {current: null | HTMLButtonElement};6
7 constructor() {8 super({});9 this.buttonRef = React.createRef<HTMLButtonElement>();10 }11
12 render(): React.Node {13 return <button ref={this.buttonRef}>Toggle</button>;14 }15}One notable difference between useRef and createRef is that createRef does not accept
a default value. It will initialize the ref with the value null. This is because
DOM elements will not exist until the first render of MyComponent and so a null value
must be used.
Again, note that the ref value is wrapped in an object with a current property.