Become a member
to unlock all features

Level Up!

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


    Using React Contexts for Nested Components


    Contexts are currently undocumented in React v0.12.2, so use at your own risk. However they provide a particularly nice solution to passing data down through nested 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




    One of the more cumbersome things about react is the need to pass your properties down through a tree of components. Here we've got a parent component, is taken in text of Hello World. We pass that to a child component in our props, and then we pass that to a grandchild component, which in the end puts it into this paragraph tag, and now puts it to the string.

    Now one way around this, and this is very undocumented this point is with context. Here is the with context function. I'm going to pass in an object with a key of text and a value of, "Hi there." Then I'm just going to output my parent component to the document.body.

    Go in comment this out. Now up here is our parent component, and in our child component we can drop this props text, or passing that into the next one. Now here in our grandchild component, instead of this.props we are going to use this.context.

    Then we need to set our context types, so whoops, context types. This works a lot like prop types, so we are just going to set text, and we are going to say that that needs to be a string. We'll save that and there we go. Our property carried all the way through that.

    Now if we don't want to wrap or render in the with context signature, we can come to our parent, and create child context types just like we did with context types. We'll show that needs to be a string, and then we can add a method called Get Child Context.

    This works a lot like state. We just return an object, key of text, and value of, "Hey there, World," save that, and awesome. Now we've passed that prop all the way down through our tree. Again I just want to mention that this is really undocumented, and there's probably a reason for that. I've definitely seen in use out in the wild, so it's available.