Register to get access to free programming courses with interactive exercises

Refs JS: React

By its very nature, React insulates you from working directly with the DOM. But it often comes to integrating third-party components not written in React. In that case, we start thinking about direct access to the DOM. Also, we need a similar mechanism for text selection, focus, and media playback.

React allows you to do this with refs. It's important to understand that this mechanism is not usually necessary. We should avoid its use as much as possible.

Consider the task of focusing on the input field:

See the Pen js_react_refs_focus by Hexlet (@hexlet) on CodePen.

Now we will discuss the component attribute ref. Its value should be the object created in the constructor through the React.createRef() function. Unlike the rest of the data in props or state, this object is stored as an object property. The name of the property can be anything you like.

This object's property current gives access to a DOM element, which you can use in componentDidMount or componentDidUpdate.

So, this.<property name>.current stores the DOM element of the component for which we set ref. In the example above, it's input: <input ref={this.textInput} />.

The DOM element gets inside current after we embed the current component in the real DOM. In other words, we can only use it in componentDidUpdate and componentDidMount, mentioned above.

Below is an example of creating a wrapper component over the popular jQuery plugin Chosen:

See the Pen js_react_refs_dom by Hexlet (@hexlet) on CodePen.

Refs can also be used on self-written components implemented as classes.

Real-world use

React is convenient and easy to work with as long as we stay in React. But most of the existing JavaScript libraries interact with the DOM directly, which effectively negates the benefits of React when using them. For example:

// https://github.com/kylefox/jquery-modal
$('#login-form').modal();

Including such libraries in a project will inevitably lead to the active use of lifecycle techniques and make the code more complex. It is why it's common to create so-called wrappers that hide all interaction with the DOM inside and expose the standard React interface, namely the props. One of these tasks is to resize the container. One solution is the react-resizable component. Take a look at how this component works:

const Resizable = require('react-resizable').Resizable; // or,
const ResizableBox = require('react-resizable').ResizableBox;

// ES6
import { ResizableBox } from 'react-resizable';

// ...
render() {
  return (
    <ResizableBox width={200} height={200} minConstraints={[100, 100]} maxConstraints={[300, 300]}>
      <span>Contents</span>
    </ResizableBox>
  );
}

Nothing in this code is reminiscent of the real DOM. It comes down to the component, wrapped in ResizableBox, that hides all the work inside itself. We use the same principle for hundreds and maybe thousands of other components available on GitHub. Some of them are:

  • react-hotkeys
  • react-stripe-elements (payment gateway)

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
Development of front-end components for web applications
10 months
from scratch
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.