Using createRef() to reference a node in a child component in React 16.3

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

In this lesson we'll use the new createRef() method to retrieve a node in a child component and pass it back to it's parent component. We'll also show how you can use a ref in a functional component with createRef().

Additional Resources: https://reactjs.org/docs/refs-and-the-dom.html#exposing-dom-refs-to-parent-components

Instructor: [00:00] In this example, I'd like to display the width of a child component from within its parent component. I have an app component which contains a box and a regular div that's expecting some state that's not hooked up yet.

[00:12] There are a few ways of doing this, but the way I'm going to do it right now is by creating a ref in the parent component and passing it down as a prop to the child component. Let's go ahead and do that.

[00:23] First, I'm going to add a property called input ref, and we'll go ahead and use React create ref to create an instance of a ref. I'm going to pass it to my box component with a new property called input ref.

[00:37] I'm going to go ahead and retrieve that property in my box component and assign it to ref on my div here. We'll do this. Notice how the child component is a functional stateless component, and we're using the ref attribute.

[00:55] Normally, you can't use refs in stateless components, but since we're passing down an instance of create ref as a property, it's good to go. The node will be attached to this ref for us to work with.

[01:06] I'll be using ResizeObserver to check the width of the node and set the state whenever the width of the child component changes. I have a polyfill for browsers that don't support ResizeObserver yet, which is all of them other than Chrome.

[01:25] There you have it. We are now retrieving a node from a child component and utilizing the width in our parent component. Keep in mind that this method of creating a ref and passing it down as a prop only works when you control the child component.