Open In App

React forwardRef

React forwardRef allows parent components to move down (or “forward”) refs to their children. It gives a child component a reference to DOM entity created by its parent component in React. This helps the child to read and modify the element from any location where it is used.

React forwardRef allows to expose a DOM node to Parent Component. It is a method that lets React forward the React refs to the child component. This technique is Forwarding Ref.

Syntax:



React.forwardRef((props, ref) => {})

Parameters:

Return Value:

How does forwardRef work in React ?

In React, parent components typically use props to transfer data down to their children. Consider you make a child component with a new set of props to change its behavior. We need a way to change the behavior of a child component without having to look for the state or re-rendering the component. We can do this by using refs. We can access a DOM node that is represented by an element using refs. As a result, we will make changes to it without affecting its state or having to re-render it.

When a child component needs to refer to its parent’s current node, the parent component must have a way for the child to receive its ref. The technique is known as ref forwarding.

React forwardRef Example:

Now write down the following code in the App.js file. Here, App is our default component where we have written our code.




// Filename - App.js
 
import React from 'react'
 
class App extends React.Component {
  constructor(props) {
    super(props)
    this.aRef = React.createRef()
  }
  render() {
    return (
      <>
        <Counter ref={this.aRef} />
        <button onClick={() => { console.log(this.aRef) }}>
         Ref
        </button>
      </>
    )
  }
}
 
const Counter = React.forwardRef((props, ref) => {
  class Counter extends React.Component {
    constructor(props) {
      super(props)
      this.state = {
        count: 0
      }
    }
    render() {
      return (
        <div>
          Count: {this.state.count}
          <button ref={ref} onClick={() => this.setState(
            { count: this.state.count + 1 })}>
                  Increment
          </button>
        </div>
      )
    }
  }
  return <Counter />
})
 
export default App

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Explanation:

The explaination to above examples is as follows:

Reference: https://reactjs.org/docs/forwarding-refs.html
 


Article Tags :