Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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


    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



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.