Be the first user to complete this post

  • 0
Add to List

Using context and childContext in React

When working with React in a deeply nested hierarchy, often times you will find yourself in a situation where you need to pass down props from the parent as is to the children and the grandchildren. Although passing down properties is great, but writing code in such a manner encourages relying on memory to pass down the necessary props, and that's not really a good use of your brain.Fortunately, React provides a way to make this task easier. React has something called as Child contexts that allows a parent element to specify a context - aka a set of properties - which can be accessed from all of its children and grandchildren via the this.context object. There are 2 aspects to how you would go about implementing this in your code.
  1. In the parent, the getChildContext method is used to return an object that is passed own as the child context. The prop types of all the keys in this object must also be defined in the childContextTypes property of the parent.
  2. Any child that needs to consume the properties passed down from its parents must whitelist the properties it wants to access via the `contextTypes' property.
Here's an example of how this works [wpgist id="e4a7eccb58e84d14e3f7" file="ReactContextTypes.jsx"] One may argue that this makes the code a bit more verbose, because now you end up creating an additional key contextTypes on every child component. However, the reality is that you can specify the `contextTypes' property on a mixin. That way you can avoid rewriting the whitelisting boilerplate code by simply using the mixin on all the child components that need to access those properties from its context.



Also Read:

  1. Pure vs Impure functions
  2. Reactjs flux architecture - Visualized
  3. webpack with babel6 and react
  4. Pass down props using React childContextTypes in a deeply nested component tree
  5. Require the css file of a package using webpack