×

React Refs

React Refs

The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and the React element. It is also an attribute that makes it possible for storing the reference to particular React elements or DOM nodes. It is used whenever we have to change the value of a child component, without using props.

Refs give you better functionality like we can use callbacks with them.

Creation of Refs

In React, we can create Refs by using React.createRef(). The ref is used for returning a reference to the element.  The following example will help you to understand how we can create refs.

import React from 'react';
 class App extends React.Component { 
  constructor(props) { 
  super(props); 
  this.referenceCalling = React.createRef(); // Method for creating Refs
  } 
  render() { 
  return <div ref={this.referenceCalling} />;  
  } 
 } 
 export default App; 

Accessing of Refs

In React, when the ref passes to an element within the render method, then a ref to the node is accessible by the current attribute of the ref.

const node = this.callRef.current;

The following examples show you the code without using refs and with refs.

Example:

Without Refs

import React from 'react';

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      written: "",
    };
  }

  update(e) {
    this.setState({ written: e.target.value });
  }

  render() {
    return (
      <div>
        <h2>Without Using refs</h2>
        <label>
          <strong>Your Input:</strong>
        </label>
        <input
          type="text"
          placeholder="Write Something"
          onChange={(e) => this.update(e)}
        />
        <p>
          <strong>Your Output:</strong> {this.state.written}
        </p>
      </div>
    );
  }
}

export default App;

In the above code, we are using the target value of event e for getting the value of the text-field. After the compilation of the above code, you will get the following output.

Output:

Without Refs

With Refs

In this example, we are making use of refs. The code of this example is as follows:

import React from 'react';

class App extends React.Component {
  constructor() {
    super();
    this.state = { written: "" };
  }

  update(e) {
    this.setState({ written: this.refs.any.value });
  }

  render() {
    return (
      <div>
        <h2>Using refs</h2>

        <div>
          <label>Your Input:</label>
          <input
            type="text"
            ref="any"
            onChange={(e) => this.update(e)}
            placeholder="Write Something"
          />
        </div>

        <div>
          <h2>Your Output = {this.state.written}</h2>
        </div>
      </div>
    );
  }
}

export default App;

Output:

Without Refs

Callback Refs

In React, “callback refs “are the way of using refs. It provides you more control when the refs are set or unset. Rather than creating the refs by using the createRef() method, there is a way for creating the refs by passing a callback function in the ref attribute of the component.

For example:

this.callRefInput = (element) => {
  return element;
};

The callback function is used for storing the reference to the DOM node within an instance property and it can be accessed elsewhere.

We can access it by using this.callRefInput.value.

The following example will help you to understand the working of the callback refs.

Example:

import React, { Component } from 'react';
import { render } from 'react-dom';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.input = null;

    // Setting a callback ref
    this.setInputRef = (element) => {
      this.input = element;
    };

    // Method to focus on the input element
    this.focusRefInput = () => {
      if (this.input) this.input.focus();
    };
  }

  componentDidMount() {
    // Autofocus the input on mount
    this.focusRefInput();
  }

  render() {
    return (
      <div>
        <h2>Example of Callback Refs</h2>
        <input
          type="text"
          ref={this.setInputRef}
          placeholder="This input will be auto-focused"
        />
        <button onClick={this.focusRefInput}>
          Click the button to focus on the input
        </button>
      </div>
    );
  }
}

export default App;

Output:

Callback Refs

Add Ref to DOM elements

The following example will show you the adding of a ref for storing the reference to a React element or DOM node.

Example:

import React, { Component } from 'react';
import { render } from 'react-dom';

function UserInput(props) {
  const refInput = React.createRef();

  function click() {
    refInput.current.focus();
  }

  return (
    <div>
      <h2>Example of Adding Ref to Functional Component</h2>
      <input type="text" ref={refInput} placeholder="Focus me on click" />
      <button onClick={click}>Focus Input</button>
    </div>
  );
}

class App extends Component {
  constructor(props) {
    super(props);
    this.refInput = React.createRef();
  }

  focusInput = () => {
    this.refInput.current.focus();
  };

  render() {
    return (
      <div>
        <h2>Example of Adding Ref to Class Component</h2>
        <input type="text" ref={this.refInput} placeholder="Focus me on click" />
        <button onClick={this.focusInput}>Focus Input</button>
        <UserInput />
      </div>
    );
  }
}

export default App;

Output:

Add Ref to DOM elements

Add Ref to class components

In the following example, we add a ref for storing the reference to the class component.

Example:

import React, { Component } from 'react'; 
import { render } from 'react-dom'; 

function UserInput(props) { 
  const refInput = React.createRef(); 

  function click() { 
    refInput.current.focus(); 
  } 

  return (
    <div>
      <h2>Example of Adding Ref to Class Component</h2>
      <input ref={refInput} type="text" placeholder="Enter text here" />
      <button onClick={click}>Focus Input</button>
    </div>
  );  
} 

class App extends React.Component { 
  constructor(props) { 
    super(props); 
    this.refInput = React.createRef(); 
  } 

  focusInput() { 
    this.refInput.current.focus(); 
  } 

  render() { 
    return ( 
      <div>
        <h2>Ref Example</h2>
        <input ref={this.refInput} type="text" placeholder="Enter text here" />
        <button onClick={() => this.focusInput()}>Focus Input</button>
      </div>
    ); 
  } 
} 

export default App;

Output:

Add Ref to class components

React With useRef()

It is introduced in the React Version 16.7 and its above version. It helps in the accessing of React Element or DOM node. It returns the object of ref whose .current property initializes to the passed argument. The returned object persists for the lifetime of the component.

Syntax:

const refContainer = useRef(initialValue);  

Example:

In the following code, the useRef function is assigned to a variable, refInput, and then it will attach to an attribute which we want to reference.

function useRefExample() { 
  const inputRef = useRef(null);

  const onButtonClick = () => {
    inputRef.current.focus();
  };

  return (
    <>
      <input ref={inputRef} type="text" placeholder="Type something here" />
      <button onClick={onButtonClick}>Submit</button>
    </>
  );
}

Refs Current Properties

There are some properties of the refs that are as follows:

  • If we use ref attribute on a custom class component, then the object of ref receives the mounted instance of component as the current property.
  • We cannot use the ref attribute as function components because they do not have instances.

When to use Refs

Refs are useful in the following cases:

  • When we require DOM measurements such as managing focus, text selection, or media playback.
  • Refs are used to trigger imperative animations.
  • Refs are used in callbacks.
  • It is used when we have to integrate with third-party DOM libraries.

When to not use Refs

  • The use of refs should be avoided when it is done declaratively. For example, you are passing an isOpen prop instead of using open() and close() methods on a dialog component.
  • The overuse of Refs should be avoided.

Related Topics

React Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 minutes read.

React CSS

What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

5 minutes read.

How to use React Context

React Context React Context is used to pass the data through the component tree without passing the props down manually at the every level. In React Application, the data is passed in a top-down approach...

4 minutes read.

React Component Life-Cycle

React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

4 minutes read.

React JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

3 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 minutes read.

React Components

React Components Former, the developers used to write more than thousands of lines of code to develop a single-page application. These applications follow the structure of traditional DOM, and it was very challenging to make...

2 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

ReactJS Versions

ReactJS Versions The Complete set of release history of ReactJS is elaborated as follows. The complete set of full documentation of recent releases is on GitHub. S.noVersionRelease DateExplanation1.0.3.029/05/2013Initially released for public.2.0.4.029/07/2013Supporting comments...

4 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 minutes read.

React Code Splitting

React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

4 minutes read.

React Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

5 minutes read.

React Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

2 minutes read.

React Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

5 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Hooks

React Hooks The Hooks were introduced in React 16.8. By using React Hooks, you can use the state and other features of the React without writing a class. Hooks do not work within the classes....

5 minutes read.

React Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 minutes read.

Comparison between React and Vue

Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

3 minutes read.