Dowemo
0 0 0 0


Question:

I'm trying to find the proper way to define some components which could be used in a generic way:

<Parent>
  <Child value="1">
  <Child value="2">
</Parent>

There is a logic going on for rendering between parent and children components of course, you can imagine <select> and <option> as an example of this logic.

This is a dummy implementation for the purpose of the question:

var Parent = React.createClass({
  doSomething: function(value) {
  },
  render: function() {
    return (<div>{this.props.children}</div>);
  }
});
var Child = React.createClass({
  onClick: function() {
    this.props.doSomething(this.props.value); // doSomething is undefined
  },
  render: function() {
    return (<div onClick={this.onClick}></div>);
  }
});

The question is whenever you use {this.props.children} to define a wrapper component, how do you pass down some property to all its children?


Best Answer:


Scenario 1 - pass props to direct children.

See all other answers

Scenario 2 - pass data / dependencies through the component tree via context

Keep reading.

React's context makes data available / enables dependency injection to all children and subchildren components, here is an example

class Child extends React.Component {
  render() {
    return (
      <div onClick={() => this.context.doSomething(this.props.value)}>
        Click Me
      </div>
    );
  }
};
// Access parent context by defining contextTypes
Child.contextTypes = {
  doSomething: React.PropTypes.func
};
class Parent extends React.Component {
  // passes the information down to its children
  getChildContext() {
    return { doSomething : this.doSomething };
  }
  doSomething(value) {
    console.log('doSomething called by child with value:', value);
  },
  render() {
    return <div>{this.props.children}</div>
  }
};
// make information available to its children
Parent.childContextTypes = {
  doSomething: React.PropTypes.func
};
ReactDOM.render(
  <Parent>
    <Child value="1" />
    <Child value="2" />
  </Parent>,
  document.getElementById('container')
);

This article.

Disclaimer: React's documentation mentions that context is an experimental API, but it hasn't changed for years now. Also, it really is needed in some cases, this is why (one of) the most famous React libraries makes use of it internally - React Router. If you want to go on the super safe side though, you might want to abstract context in some way that fits your needs.




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs