• Expose Component Functions

    Expose Component Functions

    There’s another (uncommon) way of communicating between components: simply expose a method on the child component for the parent to call.

    Say a list of todos, which upon clicking get removed. If there’s only one unfinished todo left, animate it:

    1. var Todo = React.createClass({
    2. render: function() {
    3. return <div onClick={this.props.onClick}>{this.props.title}</div>;
    4. },
    5. //this component will be accessed by the parent through the `ref` attribute
    6. animate: function() {
    7. console.log('Pretend %s is animating', this.props.title);
    8. }
    9. });
    10. var Todos = React.createClass({
    11. getInitialState: function() {
    12. return {items: ['Apple', 'Banana', 'Cranberry']};
    13. },
    14. handleClick: function(index) {
    15. var items = this.state.items.filter(function(item, i) {
    16. return index !== i;
    17. });
    18. this.setState({items: items}, function() {
    19. if (items.length === 1) {
    20. this.refs.item0.animate();
    21. }
    22. }.bind(this));
    23. },
    24. render: function() {
    25. return (
    26. <div>
    27. {this.state.items.map(function(item, i) {
    28. var boundClick = this.handleClick.bind(this, i);
    29. return (
    30. <Todo onClick={boundClick} key={i} title={item} ref={'item' + i} />
    31. );
    32. }, this)}
    33. </div>
    34. );
    35. }
    36. });
    37. ReactDOM.render(<Todos />, mountNode);

    Alternatively, you could have achieved this by passing the todo an isLastUnfinishedItem prop, let it check this prop in componentDidUpdate, then animate itself; however, this quickly gets messy if you pass around different props to control animations.