Instructor: 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.
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.
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.
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.
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.
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.
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.