Using forwardRef with React hooks

JB
JB
Jan 5 · 2 min read
Image for post
Image for post

The forwardRef hooks allows React users to pass refs to child components. The ref can be created and referenced with useRef or createRef and then passed in a parent component. Using forwardRef instead of useRef is useful when a ref needs to be accessed in a parent component.

Using forwardRef

Refs cannot be passed as props to functional components.

This will fail:

import React, {useRef} from 'react';

This will work:

import React, {useRef, forwardRef} from 'react';

Note that the child component is wrapped in parentheses and ref is separated from props to use forwardRef.

forwardRef code example

In this example, we will create a ref in a parent component so we can use it to set state, and forward the ref to a child component. This is a common use case for forwardRef.

This is simple code a parent page that has a button to open a modal and two functions: toggleModal , for opening and closing the modal using buttons, and handleOutsideClick, so the modal can be closed by clicking outside it.

> Parent component

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

Child component

import React, { forwardRef } from 'react;

That’s the syntax for forwardRef with an example. More resources can be found here:

JavaScript In Plain English

New JavaScript + Web Development articles every day.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store