On the use of refs in react

Keywords: Javascript React Attribute

In react, refs can be used to access dom, or react objects can be created in render.

The main uses of refs are

  1. Do some animation interaction
  2. Playback of Media Controls
  3. Get focus, text, etc.

There are two ways to use refs, one is to make React.createRef() API, the other is to use callback refs.

Let's start with the first approach, using React.createRef() API


import React, { Component } from 'react'
export default class App extends React.Component {
  constructor(props) {
    super(props);
    // Create a ref to store DOM elements of textInput
    this.textInput = React.createRef();
    this.focusTextInput = this.focusTextInput.bind(this);
  }

  focusTextInput() {
    // Direct use of native API s to focus text input boxes
    // Note: We access DOM nodes through "current"
    this.textInput.current.focus();
    console.log(this.textInput.current);//Here output the dom object of input
  }

  render() {
    // Tell React that we want to associate < input > ref with
    // textInput created in the constructor
    return (
      <div>
        <input
          type="text"
          ref={this.textInput} />

        <input
          type="button"
          value="Click on me to get the focus"
          onClick={this.focusTextInput}
        />
      </div>
    );
   }
 }

The second is a callback refs, which React calls when the component is mounted and passes in the DOM element, and when uninstalled, calls it and passes in null. Before a component DidMount or component DidUpdate is triggered, React ensures that ref s are always up to date.

import React, { Component } from 'react'
export default class App extends React.Component {
  constructor(props) {
    super(props);
    // Create a ref to store DOM elements of textInput
    this.textInput = null;
    this.setTextInputRef = element => {
      this.textInput = element;
    };
    this.focusTextInput = () => {
      // Use native DOM API to focus text input boxes
      if (this.textInput) this.textInput.focus();
    };
  }

  componentDidMount() {
    // After components are mounted, text boxes are automatically focused
    this.focusTextInput();
  }

  render() {
    // Use the `ref'callback function to store references to the DOM node of the text input box into React
    // Instances (such as this.textInput)
    return (
      <div>
        <input
          type="text"
          ref={this.setTextInputRef}
        />
        <input
          type="button"
          value="Click on me to get the focus"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

Later on, how do parent and child components pass refs? You can pass callback refs between components. The code is as follows

import React, { Component } from 'react'
function CustomTextInput(props) {
  return (
    <div>
      <input ref={props.inputRef} />
    </div>
  );
}

class App extends React.Component {
  constructor(props) {
    super(props);
    // Create a ref to store DOM elements of textInput
    this.inputElement = null;
    this.setTextInputRef = element => {
      this.inputElement = element;
    };
    this.focusTextInput = () => {
      // Use native DOM API to focus text input boxes
      console.log(this.inputElement)
      if (this.inputElement) this.inputElement.focus();
    };
  }
  componentDidMount() {
    // After components are mounted, text boxes are automatically focused
    this.focusTextInput();
  }
  render() {
    return (
      <div> 
      <CustomTextInput
        inputRef={el => this.inputElement = el}
      />
      <input
          type="button"
          value="Click on me to get the focus"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

In the example above, App passes its refs callback function as inputRef props to CustomTextInput, and CustomTextInput passes the same function as a special ref attribute to <input>. As a result, this.inputElement in App is set to the DOM node corresponding to the input element in CustomTextInput.

Use React. forward Ref to get the pass ref, React passes ref to the fowardRef inner function (props, ref) => as its second parameter, and then forwards it to the DOM button it renders.

import React, { Component } from 'react'
const CustomTextInput = React.forwardRef((props, ref) => (
  <div>
      <input ref={ref} />
   </div>
));

class App extends React.Component {
  constructor(props) {
    super(props);
    // Create a ref to store DOM elements of textInput
    this.inputElement = React.createRef();
    this.focusTextInput = () => {
      // Use native DOM API to focus text input boxes
      console.log(this.inputElement)
      this.inputElement.current.focus();
    };
  }

  render() {
    return (
      <div> 
      <CustomTextInput
        ref={this.inputElement}
      />
      <input
          type="button"
          value="Click on me to get the focus"
          onClick={this.focusTextInput}
        />
      </div>
    );
  }
}

Posted by izbryte on Thu, 03 Oct 2019 11:00:01 -0700