Files
react/docs/tips/14-communicate-between-components.md
T
Paul O’Shannessy dfebed11c2 Merge pull request #7308 from zpao/jekyll3
Upgrade to Jekyll 3
(cherry picked from commit 5e3959e071)
2016-07-19 16:36:23 -07:00

1.4 KiB

id, title, layout, permalink, prev, next
id title layout permalink prev next
communicate-between-components Communicate Between Components tips tips/communicate-between-components.html false-in-jsx.html expose-component-functions.html

For parent-child communication, simply pass props.

For child-parent communication: Say your GroceryList component has a list of items generated through an array. When a list item is clicked, you want to display its name:

var handleClick = function(i, props) {
  console.log('You clicked: ' + props.items[i]);
}

function GroceryList(props) {  
  return (
    <div>
      {props.items.map(function(item, i) {
        return (
          <div onClick={handleClick.bind(this, i, props)} key={i}>{item}</div>
        );
      })}
    </div>
  );
}

ReactDOM.render(
  <GroceryList items={['Apple', 'Banana', 'Cranberry']} />, mountNode
);

Notice the use of bind(this, arg1, arg2, ...): we're simply passing more arguments to handleClick. This is not a new React concept; it's just JavaScript.

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this.