Understanding forwardRef in React: A Beginner's Guide

Rohan SahuRohan Sahu
2 min read

What is forwardRef ?

forwardRef in react is a higher order component that allow us to pass a reference (ref) from parent component to child component’s DOM element.

Let's assume you have a parent component named Parent.jsx and a child component named Child.jsx. Inside the parent component, there is a button, and inside the child component, there is a div. You can change the background color of the div inside the child component by clicking the button in the parent component using forwardRef. Additionally, you can perform other DOM manipulation operations as well.

Why use forwardRef ?

To access a child components DOM elements
Normally, refs only work on native DOM elements (<input>,<button>), not custom components. forwardRef allows a parent to attach a ref to a child custom component.
Useful for Third-Party Libraries
Some UI libraries require direct DOM manipulation.

Example :

//Parent.jsx

import React, { useRef } from 'react'
import Child from './Child'

function Parent() {

    const childRef = useRef()

    const handleClick = () => {
        childRef.current.style.backgroundColor = "red"
        childRef.current.style.color = "black"
    }

    return (
        <div>
            <button onClick={handleClick}>Click</button>
            <Child ref={childRef} />
        </div>
    )
}

export default Parent
//Child.jsx

import React, { forwardRef } from 'react'

function Child(props, receivedRef) {
    return (
        <div>
            <div style={{ width: '100px', height: '100px', marginTop: '30px' }} ref={receivedRef}>
                div
            </div>
        </div>
    )
}

export default forwardRef(Child)
0
Subscribe to my newsletter

Read articles from Rohan Sahu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rohan Sahu
Rohan Sahu