Forwarding Ref in React Hooks Env

Woohyun Jang
Jul 26, 2020 · 4 min read
Photo by Caspar Camille Rubin on Unsplash

In this posting, we’re going to study about ‘useRef’ hooks and ‘forwardRef’ features while making the side menu in React App.

1. setup app and make SideMenu component

At first, setup the react hooks development environment by ‘create-react-app’.

After the app is created, we can see the App component written by typescript.

Now, let’s make a component named ‘SideMenu’.

And then, I set some CSS code to make the component visible well.

So I can see the page like this.

http://localhost:3000

2. Feature: unfold the SideMenu

Basic publishing is over. From now on, I’ll make a feature that the SideMenu folding.

At first, I need a ‘menu is visible’ state. so I made a state called ‘isSideMenuVisible’ by ‘useState’ API.

I replaced ‘a tag’ to ‘unfold side menu button’. and registered click event listener.

CSS code also needs to fix. we need to see that only it contains the ‘is-visible’ class.

When you launch the App and click the unfold button, the Sidemenu appears.

3. Feature: fold the SideMenu

Then we need a folding feature. If I click the outside of SideMenu and unfold button, the SideMenu has to fold.

So I made a ref variables and click event listener inside the useEffect.

Refs provide a way to access DOM nodes or React elements created in the render method. - React.js Doc

I made a click event listener. It calls the ‘setIsSideMenuVisible’ to set the isSideMenuVisible to false.

But if the click event target is ‘SideMenu’ component or ‘unfold button’, the callback function works nothing.

Ignore to click ‘unfold button’ is no problem like this. folding feature works well.

but the Problem is Ignore to click ‘SideMenu component’.

When we make a ref object named ‘sideMenuRef’ like ‘sideMenuButtonRef’,

we can see an error like this.

The message notice that there’s no ‘ref’ property in SideMenu component. So I added the ‘ref’ property. And then, The App was build successfully.

But there is still a problem. When I clicked the SideMenu, it is folded!

The browser console is showing that warning messages. It is recommended to use ‘React.forwardRef’. What’s this?

The ‘forwardRef’ API supports to use Ref object in children components.

If some function component is wrapped by this, the function component received two arguments that ‘props’ and ‘ref’.

So we can use that in children's components.

It’s not too difficult to use. We just have to wrap the component by ‘forwardRef’!

Because we’re using typescript, I defined types as VScode’s recommend(LegacyRef).

Now, the click event listener works well!.

Github Source Code

Weekly Webtips

Explore the world of web technologies through a series of tutorials