Understanding Forward Ref in React

Understanding Forward Ref in React

Concept of forwarding ref in react.

What is Forwarding Ref?

Forwarding Ref is a technique used to pass down a ref from components to its children components.

Steps Involved

  • Create a forward ref.
  • Attach a ref to the child component.
  • Forward the ref to the child components.

Create a ref

Here we will create a ref in a parent component called ForwardRefParent in a class-based component.

  import React from 'react'
  class ForwardRefParent extends React.Component {
     constructor(props){
           super(props) 
           this.inputRef = React.createRef()
  }
 render(){
   return (
          <div>
             <button>Focus Value </button>
          </div>
       )
   }
}

export default ForwardRefParent

Explanation

  • In the above code, we created a ref.
  • Using the React.createRef() API.

Attach a ref to the child component.

Create a child component called ForwardRefChild.

  import React from 'react'
  import ForwardRefChild from './yourfile/path'

  class ForwardRefParent extends React.Component {
     constructor(props){
           super(props) 
           this.inputRef = React.createRef()
  }
 render(){
   return (
          <div>
             <ForwardRefChild ref={this.inputRef} />
             <button>Focus Value </button>
          </div>
       )
   }

}

export default ForwardRefParent

Explanation

  • In the above code, we created a ref.
  • Passed the ref as a JSX attribute in a variable called ref in the child component.

Forward ref to the child component

Forward the ref to the child component as shown below;

const ForwardRefChild = React.forwardRef((props, ref) => {
    return (
        <div>
            <input type="text" ref={ref} />
        </div>
    )
})

export default ForwardRefChild

Explanation

  • In the above code, used the React.forward() API to forward the ref.
  • Passed the component function as a parameter to the React.forward API.
  • Passed ref as second parameter.
  • Forward ref argument down to `Passed ref as a JSX attribute.

Enable an event handler

import React, { Component } from 'react'
import ForwardRefChild from './yourfile/path/'

class ForwardRefParent extends Component {
    constructor(props) {
        super(props)
          this.inputRef = React.createRef() 
    }

    clickHandler = () => {
        this.inputRef.current.focus()
        console.log('focused')
    }
    render() {
        return (
            <div>
                <ForwardRefChild ref={this.inputRef} />
                <button onClick={this.clickHandler}>Focus value</button>
            </div>
        )
    }
}

export default ForwardRefParent

Explanation

  • In the code above, the ref is passed to the ForwardRefChild component.
  • The <button onClick={this.clickHandler}> Focus value </button> is use to focus the input.

The end.

Thanks for reading :)