codewithjohn.dev
Published on

How to use React forwardRef function

In this article, we will explore how to use React forwardRef and explore its capabilities, use cases, and best practices along with several code examples to illustrate its usage.

Table of Contents

What are refs?

Before diving into forwardRef, let's do a quick recap of what refs (or references) are in React are. React refs are a feature in React that allow you to directly access and interact with DOM elements or React components without using any selector methods of the document object. React provides a method React.createRef() that is used when creating a ref in a class based component and useRef that is used in functional components. Once a ref is created, it can be attached to React element using ref attributes.

Let's say we want to programmatically toggle the visibility of a password input when the user clicks a button. Here's a simple example of using React refs to toggle the visibility of a password input:

import React, { useRef, useState } from 'react'

function ExampleComponent() {
  const [showPassword, setShowPassword] = useState(false)
  const passwordRef = useRef(null)

  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword)
    passwordRef.current.type = showPassword ? 'password' : 'text'
  }

  return (
    <div>
      <input ref={passwordRef} type="password" />
      <button onClick={togglePasswordVisibility}>{showPassword ? 'Hide' : 'Show'} Password</button>
    </div>
  )
}

export default ExampleComponent

Why do we need forwardRef in React?

The React forwardRef function is useful when you want to access or manipulate the child component's DOM node or component instance from the parent component. By using forwardRef you can forward ref from the parent element to its child component

The syntax for using forwardRef in React is as follows:

const ForwardedComponent = React.forwardRef((props, ref) => {
  // component logic here
})

The forwardRef function takes a single argument, which is a function component. This function receives two parameters:

  1. props: The props passed to the component.
  2. ref: The ref object that is forwarded to the underlying component.

To use the forwardRef function, you need to follow a few simple steps. Let's go through them with a code example that programmatically focus an input element when the user clicks a button.

First, you need to create a child component that will receive the ref attribute from the parent component. Here's an example of a simple child component:

import React from 'react'

const ChildComponent = React.forwardRef((props, ref) => {
  return (
    <form>
        <input ref={ref} type='text'>
    </form>
  )
})

export default ChildComponent

Next, you need to create a parent component that will pass the ref attribute to the child component.

Here's an example of a parent component

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

const ParentComponent = () => {
  const childRef = useRef(null)

  const handleClick = () => {
    // Access the child component's DOM element or methods using the forwarded ref
    childRef.current.focus()
  }

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

export default ParentComponent

That's it! You have successfully used the forwardRef function in React. Now, when you click the "Focus Child Component" button in the parent component, the input field in the child component will be focused.

Conclusion

In this article, we explored how to use the React forwardRef function. The forwardRef function is useful when you want to access or manipulate the child component's DOM node or component instance from the parent component. I hope this article has provided you with a clear understanding of how to create and use the React forwardRef function. Happy coding!

Like what you are reading?