Refs
Refs allow us to directly access DOM elements that were created during the render process. Even if this is not necessary in most cases, it can be useful in handful of situations in which it is hard not to revert to using them. Examples are calculating the position or size of an element in order to display a tooltip based on them or to focus on a form field using .focus() once the component has loaded.
React has evolved over the years and so have the methods dealing with Refs. But they all have one thing in common. Refs are always defined by the ref prop of a DOM element in JSX, or to be more precise createElement().
But a word of warning before we proceed. Even though Refs exist, they should be used sparingly and only if the declarative way of re-rendering components with updated state and props does not help us. Manipulation of attributes or attribute values or adding or removing classes, event listeners or changing properties like aria-hidden should always happen declaratively using props, state, JSX and re-rendering.
However, there are a few cases in which using Refs is acceptable or even necessary. These are:
  • Setting focus on an input element (input.focus()) or calling methods such as .play() or .pause() on video or audio elements
  • Invoking imperative animations
  • Reading properties of elements currently in the DOM (e.g. .getBoundingClientRect())

String Refs

The simplest and oldest form of refs are string refs. Nowadays, it is not recommended to use them anymore as they can impact performance and might be deprecated in the future. I wanted to mention them for the sake of completeness though as they are currently still part of the official API and as you might come across them during your work with React (especially if you are working with legacy code).
In order to define a string ref, you pass prop named ref to a DOM element and pass a value to that prop in string form. The corresponding DOM element is now accessible to us using the instance method this.ref inside of the component.
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
4
class ComponentWithStringRef extends React.Component {
5
componentDidMount() {
6
this.refs.username.focus();
7
}
8
9
render() {
10
return <input type="text" ref="username" name="username" />;
11
}
12
}
13
14
ReactDOM.render(<ComponentWithStringRef />, document.getElementById('app'));
Copied!
We can use this.refs.username to gain access to the input field, and then focus it by calling this.refs.username.focus().

Callback Refs

A more flexible alternative to string refs are the so-called callback refs. While being more flexible, their handling is slightly more cumbersome and needs to be managed explicitly. Using callback refs, it is possible to pass refs to a component's child components and access their corresponding DOM elements.
As the name might suggest, callback refs are declared using callback form. During Mounting, they only receive a single parameter: the DOM element or, if applied to a React component, its instance. We call the callback again during Unmounting but with null as a single parameter.
How you are using callback refs specifically is up to you, however it is a convention to save the reference to the DOM element as an instance property to be able to access it from anywhere inside the component.
Applying this to the above example, we end up with the following code:
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
4
class ComponentWithCallbackRef extends React.Component {
5
usernameEl = null;
6
7
componentDidMount() {
8
this.usernameEl.focus();
9
}
10
11
setUsernameEl = (el) => {
12
this.usernameEl = el;
13
};
14
15
render() {
16
return <input type="text" ref={this.setUsernameEl} name="username" />;
17
}
18
}
19
20
ReactDOM.render(<ComponentWithCallbackRef />, document.getElementById('app'));
Copied!
Callback refs can also be used in child components and the refs can then also be accessed in their parent components. In order to do this, you pass the callback function of the child component a prop which is not allowed to be called ref (as this is a reserved word):
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
4
class UsernameInput extends React.Component {
5
render() {
6
return <input type="text" name="username" ref={this.props.inputRef} />;
7
}
8
}
9
10
class ComponentWithRefChild extends React.Component {
11
componentDidMount() {
12
this.usernameEl.focus();
13
}
14
15
usernameEl = null;
16
17
setUsernameRef = (el) => {
18
this.usernameEl = el;
19
};
20
21
render() {
22
return (
23
<div>
24
Username:
25
<UsernameInput inputRef={this.setUsernameRef} />
26
</div>
27
);
28
}
29
}
30
31
ReactDOM.render(<ComponentWithRefChild />, document.getElementById('app'));
Copied!
If you were to name the prop ref, leaving us with <UsernameInput ref={this.setUsernameRef} />, you would end up with a reference to the UsernameInput instance instead of its input element. If we used a Function component, UsernameInput would have been null as Function components cannot be instantiated.
However, if forwarding refs to child components is something you are trying to achieve, you are better off using the forwardRef() method. I will explain it at the end of this chapter.

Refs via createRef()

With React 16.3, we have seen the introduction of the top-level API method React.createRef(). It resembles the usage of callback refs but differs in a few cases. As was the case with callback refs, you also need to take care of ref handling yourself and it is still common practice to assign the ref to an instance property.
Instead of passing an almost identical method in the form of (el) => { this.property = el } each time, the reference is already created during the instantiation of the component which is then given to the ref prop of the element.
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
4
class ComponentWithCreatedRef extends React.Component {
5
usernameEl = React.createRef();
6
7
componentDidMount() {
8
this.usernameEl.current.focus();
9
}
10
11
render() {
12
return <input type="text" name="username" ref={this.usernameEl} />;
13
}
14
}
15
16
ReactDOM.render(<ComponentWithCreatedRef />, document.getElementById('app'));
Copied!
While this looks very similar to callback refs, there is an apparent difference: you access the reference via this.usernameEl.current.
The reference to the element is not saved in the instance property which you assign the ref to, but in its .current() property. Apart from this, the behavior of createRef() is similar to that of callback refs. They can still be passed to child components via props and the DOM element can be accessed in the parent component.
To have a direct comparison — this was the use case with callback refs:
1
class MyComponent extends React.Component {
2
usernameEl = null;
3
4
render() {
5
return (
6
<input
7
ref={(el) => {
8
this.usernameEl = el;
9
}}
10
/>
11
);
12
}
13
}
Copied!
And this is the reference created with React.createRef():
1
class MyComponent extends React.Component {
2
usernameEl = React.createRef();
3
4
render() {
5
return <input ref={this.usernameEl} />;
6
}
7
}
Copied!
We are accessing the element via this.usernameEl.current.

Ref forwarding

Ref forwarding (references to a component or a DOM element) enables passing a reference through a component to a child component. In most cases, this will not be necessary but it can become of interest if you are creating reusable component libraries.
A ref is forwarded via React.forwardRef() and is passed a function as a parameter during this process. The ref itself passes props as well as the ref to it.
This sounds incredibly cumbersome, so let us look at an example instead. Let us first implement an Input component without a forwardRef:
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
4
const UsernameField = (props) => (
5
<div className="myInput">
6
<input ref={props.ref} {...props} />
7
</div>
8
);
9
10
class App extends React.Component {
11
usernameEl = React.createRef();
12
13
componentDidMount() {
14
console.log(this.usernameEl);
15
}
16
17
render() {
18
return (
19
<div className="App">
20
<UsernameField ref={this.usernameEl} />
21
</div>
22
);
23
}
24
}
25
26
ReactDOM.render(<App />, document.getElementById('root'));
Copied!
In this case, componentDidMount() does not have access to our input field from the UsernameField component. Instead, the instance of the component would actually be the ref itself. As UsernameField is a Function component, we do not even have an instance of the component. The associatedconsole.log result would be: { current: null } - not exactly ideal if we want to gain access to the input element in order to focus on it.
It is sufficient in this case to wrap the UsernameField component with a React.forwardRef() call. We can now amend the code of the UsernameField in the above example:
1
const UsernameField = React.forwardRef((props, ref) => (
2
<div className="myInput">
3
<input ref={ref} {...props} />
4
</div>
5
));
Copied!
We have thus informed React that it should forward the ref prop on the UsernameField in our App component to the component. It is passed the ref as a second parameter of the function and can pass this ref to any other element in the DOM or to another component.
If the ref is passed to a component lower in the component tree, the same restrictions apply: The relevant component either has to be a class component (then the reference would point to the instance of the class) or the component needs to conduct ref forwarding via forwardRef().

Be careful with Higher Order Components!

Careful consideration and care needs to be taken with refs while implementing Higher Order Components. If there is doubt whether these HOC should be able to access forwarded Refs, they also need to be wrapped by a forwardRef() call.
Let's extend our example from above and assume that we want to create a HOC to show all of our form elements in a unified layout. Thus, a HOC withInputStyles is created which can wrap input elements in which it is possible to assign them a ref.
This procedure is a little complicated and I have found it a little complicated to explain this properly in written form without confusing the reader further. Instead, I invite you to inspect the following code closely and read its associated comments. As soon as the idea of Higher Order Components and forwardRefs begins to make sense, the example should be sufficient to understand the actual explanation. And if it is not clear from the get go: this case is so incredibly rare that you will not need it much in practice.
So let's look at the example of forwardRef and Higher Order Components:
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
4
const withInputStyles = (InputComponent) => {
5
class WithInputStyles extends React.Component {
6
render() {
7
// We access the forwarded Ref in the props of the component
8
const { forwardedRef, ...props } = this.props;
9
10
// ... and use it as the ref for the component wrapped by the HOC
11
return (
12
<InputComponent
13
{...props}
14
ref={forwardedRef}
15
style={{ border: '2px solid black', padding: 8 }}
16
/>
17
);
18
}
19
}
20
21
// We return a forwardRef from the HOC
22
return React.forwardRef((props, ref) => (
23
// We pass the ref as the temporary prop "forwardRef"
24
<WithInputStyles {...props} forwardedRef={ref} />
25
));
26
};
27
28
// Here, we pass the ref of our component to a regular React.forwardRef() call
29
const UsernameField = React.forwardRef((props, ref) => (
30
<input ref={ref} {...props} />
31
));
32
33
// Here, we connect the HOC to the UsernameField component
34
const StyledUsername = withInputStyles(UsernameField);
35
36
class App extends React.Component {
37
// Here we are creating the Ref as we usually do and to access it later
38
usernameEl = React.createRef();
39
40
componentDidMount() {
41
this.usernameEl.current.focus();
42
}
43
44
render() {
45
return (
46
<div>
47
<StyledUsername ref={this.usernameEl} />
48
</div>
49
);
50
}
51
}
Copied!
Last modified 1yr ago