This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Using React Contexts for Nested Components

    Joe MaddaloneJoe Maddalone

    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.

    reactReact
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:01 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.

    00:23 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.

    00:41 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.

    00:59 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.

    01:18 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.

    01:37 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.

    Discuss

    Discuss