Refs (accessing the DOM)

ref – https://reactjs.org/docs/refs-and-the-dom.html

There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Refs are created using React.createRef() and attached to React JSX elements via the ref attribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.

When a ref is passed to an element in render, a reference to the node becomes accessible at the current attribute of the ref.

When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.

When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.
You may not use the ref attribute on function components because they don’t have instances.

In our CustomTextInput:

1) create a ref using React.createRef() and assign it to this.textInput

2) in render, assign an input control’s ref attribute to our this.textInput.
This creates a current property in our this.textInput and assigns the node of that input control to it.

3) For demo purposes, we want to show we can now control the input by programmatically putting a focus on it.
We do this by writing a method called focusTextInput. We create a button. Whenever that button is clicked, it sends
an event to our focusTextInput. In turn our focusTextInput uses our ref to programmatically put focus onto our input control.

You can also use it on component lifecycle functions like so:

However, you can only use it on class component because there is an instance.

In functional components, you cannot use it because there is no instance:

If you want to allow people to take a ref to your function component, you can use forwardRef.

You can, however, use the ref attribute inside a function component as long as you refer to a DOM element or a class component:

Forward Refs

Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child.

Callback Refs

React also supports another way to set refs called “callback refs”, which gives more fine-grain control over when refs are set and unset.

Instead of passing a ref attribute created by createRef(), you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.