dillon1000/react

Commit

Contexts

Summary:
adds `this.context` which you can think of as implicit props, which are passed automatically down the //ownership// hierarchy.

Contexts should be used sparingly, since they essentially allow components to communicate with descendants (in the ownership sense, not parenthood sense), which is not usually a good idea. You probably would only use contexts in places where you'd normally use a global, but contexts allow you to override them for certain view subtrees which you can't do with globals.

The context starts out `null`:

  var RootComponent = React.createClass({
    render: function() {
      // this.context === null
    }
  });

You should **never** mutate the context directly, just like props and state.

You can change the context of your children (the ones you own, not `this.props.children` or via other props) using the new `withContext` method on `React`:

  var RootComponent = React.createClass({
    render: function() {
      // this.context === null
      var children = React.withContext({foo: 'a', bar: 'b'}, () => (
        // In ChildComponent#render, this.context === {foo: 'a', bar: 'b'}
        <ChildComponent />
      ));
      // this.context === null
    }
  });

Contexts are merged, so a component can override its owner's context **for its children**:

  var ChildComponent = React.createClass({
    render: function() {
      // this.context === {foo: 'a', bar: 'b'} (for the caller above)
      var children = React.withContext({foo: 'c'},() => (
        // In GrandchildComponent#render,
        // this.context === {foo: 'c', bar: 'b'}
        <GrandchildComponent />
      ));
      // this.context === {foo: 'a', bar: 'b'}
    }
  });
Browse files
Changed paths11 files
First-parent comparison
M src/addons/transitions/ReactTransitionableChild.js ModifiedM src/core/React.js ModifiedM src/core/ReactCompositeComponent.js ModifiedA src/core/ReactContext.js AddedA src/core/ReactPropTypeLocations.js AddedM src/core/ReactPropTypes.js ModifiedM src/core/__tests__/ReactCompositeComponent-test.js ModifiedM src/core/__tests__/ReactPropTypes-test.js ModifiedM src/dom/components/ReactDOMInput.js ModifiedM src/dom/components/ReactDOMTextarea.js ModifiedM src/test/reactComponentExpect.js Modified
Patch

Files changed

Rendering syntax-highlighted changes…