Using ref Attribute

The ref attribute makes it possible to store a reference to a particular React element or component returned by the component render() configuration function. This can be valuable when you need a reference, from within a component, to some element or component contained within the render() function.

To make a reference, place the ref attribute with a function value on any React element or component. Then, inside of the function, the first parameter within the scope of the function will be a reference to the element or component the ref is on.

For example in the code below I am console logging the reference out for each ref.

source code

Notice (see console) that references to components return component instances while references to React elements return a reference to the actual DOM element in the HTML DOM (i.e., not a reference to the virtual DOM, but the actual HTML DOM).

A common use for ref‘s are to store a reference on the component instance. In the code below I use the ref callback function on the text <input> to store a reference on the component instance so other instance methods have access to the reference via this (i.e., this.textInput.focus()).

source code

Notes

  • Refs can’t be attached to a stateless function because the component does not have a backing instance.
  • You might see a ref attribute with a string instead of a function; this is called a string ref and will likely be deprecated in the future. Function refs are preferred.
  • The ref callback function is called immediately after the component is mounted.
  • References to a component instance allow one to call custom methods on the component if any are exposed when defining it.
  • Writing refs with inline function expressions means React will see a different function object on every update, ref will be called with null immediately before it’s called with the component instance. I.e., when the referenced component is unmounted and whenever the ref changes, the old ref will be called with null as an argument.
  • React makes two suggestions when using refs: “Refs are a great way to send a message to a particular child instance in a way that would be inconvenient to do via streaming Reactive props and state. They should, however, not be your go-to abstraction for flowing data through your application. By default, use the Reactive data flow and save refs for use cases that are inherently non-reactive.” and “If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to “make things happen” in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to “own” that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use refs to “make things happen” – instead, the data flow will usually accomplish your goal.”