An in-depth introduction to React refs

An in-depth introduction to React refs

1. What is

Refs is called Resilient File System (ReFS) in computers.

Refs in React provide a way to allow us to access DOM nodes or React elements created in render method

The essence is the component instance returned by ReactDOM.render() . If it is a rendered component, it returns the component instance. If it is a dom rendering, it returns the specific dom node.

2. How to use

There are three ways to create ref :

  • Pass in a string and get the corresponding element in the format of the string passed in by this.refs.
  • The object is passed in. The object is created by React.createRef(). When used, the current attribute in the created object is the corresponding element.
  • Pass in a function that will be called back when the DOM is mounted. This function will pass in an element object that can be saved by itself. When used, just get the previously saved element object directly.
  • Pass in the hook, the hook is created by the useRef() method, and when used, the current attribute of the generated hook object is the corresponding element

Passing in a string

Just need to add the ref attribute in the corresponding element or component

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref="myref" />;
  }
}

The way to access the current node is as follows:

this.refs.myref.innerHTML = "hello";

Incoming Object

refs are created with React.createRef() , and then ref attribute is added to the React element, as follows:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

When ref is passed to an element in render , a reference to that node is accessible in current property of ref

const node = this.myRef.current;

Passing in a function

When ref is passed as a function, during the rendering process, the callback function parameter will pass in an element object, and then save the object through the instance

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={element => this.myref = element} />;
  }
}

To get the ref object, you only need to pass the previously stored object.

const node = this.myref

Passing in hooks

Create a ref through useRef , the overall usage is consistent with React.createRef

function App(props) {
  const myref = useRef()
  return (
    <>
      <div ref={myref}></div>
    </>
  )
}

Getting the ref attribute is also done through current attribute of hook object

const node = myref.current;

In the above three cases, ref attribute is used on native HTML elements. If the component set by ref is a class component, ref object receives the mounted instance of the component.

Note that you cannot use the ref attribute on function components because they do not have instances.

3. Application Scenarios

In some cases, we update components by using refs , but this approach is not recommended. In more cases, we re-render child elements by using props and state .

Excessive use of refs will expose component instances or DOM structures, violating the principle of component encapsulation.

For example, avoid exposing open() and close() methods in Dialog component, it is better to pass isOpen property

But refs are very useful in the following scenarios:

  • Focus control, content selection, and control of Dom elements
  • Content setting and media playback of Dom elements
  • Operations on DOM elements and component instances
  • Integrate third-party DOM libraries

This is the end of this article about understanding React refs. For more information about understanding React refs, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the use of Refs in React's three major attributes
  • Summary of some common uses of refs in React
  • Tutorial on using refs in React
  • Detailed explanation of the use of React component refs
  • Do you know the Refs attribute in React?

<<:  How to install suPHP for PHP5 on CentOS 7 (Peng Ge)

>>:  Solution to the Multiple primary key defined error in MySQL

Recommend

Example code for implementing page floating box based on JS

When the scroll bar is pulled down, the floating ...

Making a simple game engine with React Native

Table of contents Introduction Get started A brie...

Docker primary network port mapping configuration

Port Mapping Before the Docker container is start...

Implementation of CSS sticky footer classic layout

What is a sticky footer layout? Our common web pa...

How to use MySQL group by and order by together

Suppose there is a table: reward (reward table), ...

How to query duplicate data in mysql table

INSERT INTO hk_test(username, passwd) VALUES (...

Tutorial on how to quickly deploy clickhouse using docker-compose

ClickHouse is an open source column-oriented DBMS...

Parsing Apache Avro Data in One Article

Abstract: This article will demonstrate how to se...

IIS7~IIS8.5 delete or modify the server protocol header Server

Requirements: Remove HTTP response headers in IIS...

HTML tags list and usage instructions

List of HTML tags mark type Name or meaning effec...

Will this SQL writing method really cause the index to fail?

Preface There are often some articles on the Inte...

A detailed introduction to HTML page loading and parsing process

The order in which the browser loads and renders H...

8 powerful techniques for HTML web page creation

<br />Although there are many web page creat...