React Refs

React supports a very special propertyRef, which you can use to bind to any component output by render().

This special property allows you to reference the corresponding backing instance returned by render(), ensuring that you always get the correct instance at any time.

In React, refs provide a way to access DOM elements or component instances. Using refs, you can directly manipulate DOM elements or get child component instances, suitable for scenarios like handling focus, text selection, media playback, triggering forced animations, or integrating third-party DOM libraries.

Usage

Use React.createRef or useRef to create and access refs.

React.createRef is typically used in class components, while useRef is a Hook typically used in function components.

Additionally, binding this in event handler functions can be done using class property syntax to avoid creating a new function on each render.

  • Creating a Ref: Use it in the constructor of a class componentReact.createRefCreate a ref object and assign it to a property of the component instance.
  • Binding the Ref: In therendermethod, bind the ref object to the DOM element that needs to be referenced.
  • Accessing the Ref: In other methods of the component, throughthis.myInputRef.currentaccess the bound DOM element and manipulate its properties and methods.

Complete Example

You can use this to get the current React component, or use ref to get a reference to the component, as shown in the following example:

React Example

class MyComponent extends React.Component { constructor(props) { super(props); this.myInputRef = React.createRef(); } handleClick = () => { //Use the native DOM API to get focus this.myInputRef.current.focus(); } render() { return ( <div> <input type="text" ref={this.myInputRef} /> <input type="button" value="Click me to focus the input box" onClick={this.handleClick} /> </div> ); } }

Try it yourself »

In the example, we obtained a reference to the backing instance of the input field, and after clicking the button, the input field gets focus.

We can also use the getDOMNode() method to get the DOM element.


Creating Refs

React provides the React.createRef method to create refs.

Example

import React from 'react';
import ReactDOM from 'react-dom';

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

  componentDidMount() {
    this.myRef.current.focus();
  }

  render() {
    return <input type="text" ref={this.myRef} />;
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
// Render the MyComponent component
root.render(<MyComponent />);

Callback Refs

Another way to create refs is to use a callback function. This approach was common before React 16.3; now React.createRef is more recommended.

Example

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.setMyRef = element => {
      this.myRef = element;
    };
  }

  componentDidMount() {
    if (this.myRef) {
      this.myRef.focus();
    }
  }

  render() {
    return <input type="text" ref={this.setMyRef} />;
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
// Render the MyComponent component
root.render(<MyComponent />);

Accessing DOM Elements with Refs

Through Refs, you can directly access and manipulate DOM elements.

Example

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

  handleClick = () => {
    this.myRef.current.style.backgroundColor = 'yellow';
  };

  render() {
    return (
      <div>
        <input type="text" ref={this.myRef} />
        <button onClick={this.handleClick}>Change Background</button>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
// Render the MyComponent component
root.render(<MyComponent />);

Accessing Child Component Instances with Refs

Refs can also be used to access the instance methods or properties of child components.

Example

class ChildComponent extends React.Component {
  focusInput = () => {
    this.inputRef.current.focus();
  };

  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  render() {
    return <input type="text" ref={this.inputRef} />;
  }
}

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

  handleClick = () => {
    this.childRef.current.focusInput();
  };

  render() {
    return (
      <div>
        <ChildComponent ref={this.childRef} />
        <button onClick={this.handleClick}>Focus Child Input</button>
      </div>
    );
  }
}

const root = ReactDOM.createRoot(document.getElementById("root"));
// Render the MyComponent component
root.render(<MyComponent />);

Using the useRef Hook (Function Components)

In function components, you can use the useRef Hook to create refs.

Example

import React, { useRef } from 'react';
import ReactDOM from 'react-dom';

const MyComponent = () => {
  const inputRef = useRef(null);

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

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
// Render the MyComponent component
root.render(<MyComponent />);

Summary

  • Creating Refs: Use in class componentsReact.createRef, use in function componentsuseRef Hook。
  • Accessing DOM Elements: Directly access and manipulate DOM elements through refs.
  • Accessing Child Component Instances: Access child component instance methods or properties through refs.
  • Customizing Exposed Instance Values: UseuseImperativeHandleandforwardRefto customize the instance value that a child component exposes to its parent.
  • Refs in Concurrent Mode: Refs still work normally in concurrent mode and can be combined withuseTransitionand other Hooks related to concurrent mode.
Other Extensions