How to Use React Refs

How to utilise refs in React, with ref forwarding, callback refs and HOCs

Ross Bulat
9 min readApr 13, 2019

--

React Refs are a useful feature that act as a means to reference a DOM element or a class component from within a parent component. This then give us a means to read and modify that element.

Perhaps the best way to describe a ref is as a bridge; a bridge that allows a component to access or modify an element a ref is attached to. Using refs give us a way to access elements while bypassing state updates and re-renders; this can be useful in some use cases, but should not be used as an alternative to props and state (as the official React docs point out). Nevertheless, refs work well in certain scenarios that we will visit in this article.

Refs also provide some flexibility for referencing elements within a child component from a parent component, in the form of ref forwarding — we will also explore how to do this here, including how to inject refs from HOCs into their wrapped components.

Refs at a high level

Refs are usually defined in the constructor of class components, or as variables at the top level of functional components, and then attached to an element in the render() function. Here is a bare-bones example where we are creating a ref and attaching it to an <input> element:

class MyComponent extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef();
}
...
render() {
return (
<>
<input
name="email"
onChange={this.onChange}
ref={this.myRef}
type="text"
</>
)
}
}

Refs are created using React.createRef(), and are assigned to class properties. In the above example the ref is named myRef, which is then attached to an <input> DOM element.

Once a ref is attached to an element, that element can then be accessed and modified through the ref.

Let’s add a button to our example. We can then attach an onClick handler that will utilise myRef to focus the <input> element it is attached to:

...handleClick = () => {
this.myRef.current.focus();
}

--

--

Ross Bulat

Programmer and Author. @ Parity Technologies, JKRB Investments