Using React Contexts for Nested Components

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 9 years ago
Updated 5 years ago

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.

[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.

Marcus
Marcus
~ 9 years ago

Coming from AngularJS, this looks like an inherited scope, whereas using props seems to be more as the isolated wcope. When working with larger projects, nesting will not scale well. If you have a structure App > Menu > Login and you have stuff in your App used by Login, that's just a bit confusing, but bad enough.

But then we add a component in another part of the structure App > ... > LockedArticle that depends on that same nested state. A programmer will have to trace down who does what and when. This is exactly what Flux was made to avoid according to their web page.

Markdown supported.
Become a member to join the discussionEnroll Today