How to use forwardRef in react - easy explanation

How to use forwardRef in react - easy explanation

After you complete reading this post you will have no problem understanding the usage of forwardRef in react.

Generally, you'd use useRef to refer to an HTML element. But what if you would want to refer to an element that belongs to a child component? You may think you would pass a prop to the child component to assign a ref to the desired HTML element. But in that case, react will not perceive it to be a ref. So the question is, how would you pass a ref to the child component? Here forwaredRef comes into play.

// Child.js
export default function Child() {
  return (
    <div className="child">
      <h1>This is a Child Component</h1>
      <input type="text" />
    </div>
  )
}

//App.js
import "./styles.css"
import Child from "./components/Child"

export default function App() {
  return (
    <div className="App">
      <h1>Hello Abeer</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Child />
    </div>
  )
}

Suppose we want to give a ref to the input element of the Child component and do something with it from App.js file. So, to do that we need to wrap the Child component stuffs within forwardRef and also place ref as the second argument:

// Child.js
import { forwardRef } from "react" 

export default forwardRef(function Child(props, ref) {
  return (
    <div className="child">
      <h1>This is a Child Component</h1>
      <input ref={ref} type="text" />
    </div>
  )
})

ref is received from parent and denoting input.

Now we can pass the ref to the Child component from parent App.js:

//App.js
import "./styles.css"
import Child from "./components/Child"
import {useRef} from "react"

export default function App() {
    const inputRef = useRef(null)

    const handle = () => {
    inputRef.current.focus()
  }
  return (
    <div className="App">
      <h1>Hello Abeer</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Child ref={inputRef} />
            <button onClick={handle}>Handle</button>
    </div>
  )
}

Now we are making an event happen in child component from parent’s handle function. Here is a thing to remember that you can receive only one ref in Child components

Congratulations, now you know how to use forwardRef in react.

By the way, this is my first blog post.