React Refs and DOM

Sneha Mallik
Last Updated: May 13, 2022

Introduction 

If you are updated to the trends over the last few years, you've probably seen that now the focus is mostly on JavaScript frameworks like React, Ember.js, Angular, and Vue.js for developing modern applications.

One thing these frameworks have in common is that they're both built on a component-based architecture. Because most DOM(Document Object Model)-based interactions are encapsulated within the component, it's more usual to hear about components these days than it is to hear about DOM-based interactions.

While these current JavaScript frameworks can achieve a lot with their built-in functionality, there are instances when you need to connect with the actual DOM for native behavior. Most current frameworks, including React, have APIs(Application Programming Interface) for accessing your application's native DOM representation.

We'll look at how to interact with the DOM in a React application in this blog of React refs and DOM. We will look at how to use the React.createRef() functionality, which was added in React 16.3, as well as the useRef hook, which was added in a later version of React. Let us know more about React refs and DOM.

What are the React refs and DOM?

React has a feature called refs that allows components to access the DOM. Attaching a ref to an element in your application enables you to access the element's DOM from anywhere in your component.

Not only can Refs be used to provide direct access to DOM nodes, but they are also used to provide direct access to React elements. The following is what the React documentation says about react refs and DOM:

“Refs allow you to access DOM nodes or React elements that were produced during the render process.”

In general, refs should only be considered when the needed interaction cannot be done using state and props techniques.

However, there are a few instances where utilizing a reference is necessary. For example, when integrating with third-party DOM libraries. Deep interactions, such as handling text choices or managing media playback behavior, also require references on the relevant elements.

React Refs

Refs are a React function that allows you to access the DOM element and any React elements you've generated on your own. They are used when we need to update the value of a child component without using props or anything. They also give us a lot of flexibility and good functionality because we can use callbacks with them.

DOM

The Document Object Model (DOM) is a standard logical representation of any webpage developed by the World Wide Web Consortium. In simpler terms, DOM is a tree-like structure that contains all of a website's elements and characteristics as nodes. The Document Object Model (DOM) is a language-independent interface for accessing and modifying the content of any element on a webpage.

How to create Refs?

There are three main ways to make refs in React. Starting with the oldest, here is a list of the various methods:

  • String references (legacy method)

String refs are the standard means of creating refs in a React application. This is the oldest approach and is considered legacy or deprecated because it will be removed in future React releases.

String refs are easily created by adding a ref prop to the desired element and setting the value to a string name for the ref. Here's an example:

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.toggleInputCase = this.toggleInputCase.bind(this);
    this.state = { uppercase: false };
  }
  
  toggleInputCase() {
    const isUpper = this.state.uppercase;
    
    // Accessing ref using this.refs.inputField
    const value = this.refs.inputField.value;
    
    this.refs.inputField.value =
      isUpper
        ? value.toLowerCase()
        : value.toUpperCase();
        
    this.setState({ uppercase: !isUpper });
  }

  render() {
    return (
      <div>
        {/* Create a string ref named: inputField */}
        <input type="text" ref="inputField" />
        
        <button type="button" onClick={this.toggleInputCase}>
          Toggle Case
        </button>
      </div>
    );
  }
  
}

 

  • Callback refs

Instead of giving the ref's name as a string, callback refs employ a callback function to create them. This should be your preferred method of establishing refs if you're using React versions prior to version 16.3.

The React component instance or the HTML DOM element is passed as an argument to the callback method, which can be kept and accessed elsewhere. Our previous code snippet will be transformed into the following using a callback ref.

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.toggleInputCase = this.toggleInputCase.bind(this);
    this.state = { uppercase: false };
  }
  
  toggleInputCase() {
    const isUpper = this.state.uppercase;
    
    // Accessing the ref using this.inputField
    const value = this.inputField.value;
    
    this.inputField.value =
      isUpper
        ? value.toLowerCase()
        : value.toUpperCase();
        
    this.setState({ uppercase: !isUpper });
  }

  render() {
    return (
      <div>
        {/* Create a callback ref and store it in this.inputField */}
        <input type="text" ref={elem => this.inputField = elem} />
        
        <button type="button" onClick={this.toggleInputCase}>
          Toggle Case
        </button>
      </div>
    );
  }
}

 

  • 'React.createRef' (from React 16.3)

Since React 16.3, the React API has provided a createRef() method that can be used to create refs in the same way that the callback function could be used. You simply call React.createRef() to create a ref and then assign it to an element.

Here's what our previous example would look like if we used React.createRef():

class MyComponent extends React.Component {

  constructor(props) {
    super(props);
    this.inputField = React.createRef();
    this.toggleInputCase = this.toggleInputCase.bind(this);
    this.state = { uppercase: false };
  }
  
  toggleInputCase() {
    const isUpper = this.state.uppercase;
    
    // Accessing the ref using this.inputField.current
    const value = this.inputField.current.value;
    
    this.inputField.current.value =
      isUpper
        ? value.toLowerCase()
        : value.toUpperCase();
        
    this.setState({ uppercase: !isUpper });
  }

  render() {
    return (
      <div>
        {/* Reference the ref from this.inputField */}
        <input type="text" ref={this.inputField} />
        
        <button type="button" onClick={this.toggleInputCase}>
          Toggle Case
        </button>
      </div>
    );
  }
}

 

  • The 'useRef' Hook (from React 16.8)

The Hooks API has become the de facto way of abstracting and reusing code in React apps since its release in React v16. useRef is an example of a Hook that allows us to build and use refs in functional components.

Since we can't construct instances of functions, even with the useRef Hook, you can't use the ref attribute on functional components by default. 

To use the useRef Hook, simply call it and supply it the object that ref.current should refer to. This Hook call should return a ref object, which we can use in the same way as the createRef method.

const MyComponent = () => {
    const [uppercase, setUppercase] = React.useState(false)
    const inputField = React.useRef(null)
    const toggleInputCase = () => {
        // Accessing the ref using inputField.current
        const value = inputField.current.value;
        inputField.current.value = uppercase ? value.toLowerCase() : value.toUpperCase();
        setUppercase(previousValue => !previousValue)
    }

    return(
      <div>
          {/* Reference the ref from this.inputField */}
          <input type="text" ref={inputField} />
          <button type="button" onClick={toggleInputCase}>
                Toggle Case  
          </button>
      </div>
    );
  }
}

Access React Refs

When a ref is supplied to an element inside a render method in React, the current attribute of the ref can be used to get a reference to the node.

const node = this.callRef.current;  

What is ReactDOM?

ReactDOM is a package that provides DOM-specific methods that may be used at the top level of a web application to efficiently control the web page's DOM elements. The following methods are available for developers in ReactDOM's API:-

  • render()
  • findDOMNode()
  • unmountComponentAtNode()
  • createPortal()
  • hydrate()

Prerequisites for ReactDOM

To use ReactDOM in a React website or application, we must first import it from the react-dom package using the code snippet below:

import ReactDOM from 'react-dom';

Refs: Uncontrolled Components

Since React is responsible for handling updates to the component when form data changes, all components in React are controlled by default.

Refs come in helpful when dealing with uncontrollable components in React. This is because you rely on refs to acquire form values from the DOM rather than event handlers to update the state when the form data changes.

Frequently Asked Questions

 

  1. What do you mean by React Refs?

Ans: In React, the shorthand for references is called 'refs' refs are similar to keys. It is a property that allows you to save a reference to specific DOM nodes or React elements. It simply allows us to access React DOM nodes or React elements and interact with them. It is used when we don't want to use props when updating the value of a child component.

 

2. When is it required to use Refs?

Ans: There are a couple of good uses for refs:

  • Focus, text selection, and media playing can all be managed.
  • Imperative animations are triggered.
  • Third-party DOM libraries also are integrated.
  • It can be used in callbacks.

Do not use refs for something that can be done declaratively. Refs should not be used with functional components as they lack instances.

Instead of using open() and close() methods on a Dialog component in React, use the 'isOpen' property instead.

 

3. Define the current properties of Refs?

Ans: The ref value varies depending on the node type:

  • The ref is created using React.createRef() when the ref attribute is utilised in an HTML element. The current property of React.createRef() is the underlying DOM element.
  • If a custom class component has the ref attribute, the ref object receives the mounted instance of the component as its current property.
  • The function components do not have instances, so the ref attribute can't be used on them.

 

4. What are the issues related to callback refs?

Ans: The issue with callback refs is that if the callback ref is an inline function, it will be called twice during updates, once with null and once with the DOM element. Because each render creates a new instance of the function, React needs to clear the old ref and set up the new one. We can avoid this by making the callback ref a bound method on the class, but in most circumstances, this isn't necessary.

Key Takeaways

In this blog, we went over the fundamentals of React refs and dom. We also considered various techniques in which we will be able to interact with the react refs and DOM in a react application. We also learned how to use the new 'React.createRef()' and 'useRef' Hook, which React introduced to simplify the process of creating Refs.

Enroll in our Advance Front-end Web Development Course- React.js to deeply understand the concept of React refs and dom in Web Development. 

Credits: GIPHY

Happy Developing!

Was this article helpful ?
0 upvotes