1
votes

I have component A and B. Component A pass state as prop to component, says it's named show

so in my component B's render function it will be like this

{this.props.show &&
   <div>popup content</div>
}

But how I close it now? I have to pass a flag from component B to the parent? as I know it react you can pass stuff back to parent.

2
found a nice article about communication between react components ctheu.com/2015/02/12/… - imdzeeshan

2 Answers

9
votes

In order to pass data from a child to a parent, the parent needs to pass a function capable of handling that data to the child.

var Parent = React.createClass({

    getData: function(data){
         this.setState({childData: data});     
    }

    render: function(){
        return(
            <Child sendData={this.getData} />
        );
    }

});

var Child = React.createClass({

    textChange: function(event){
        this.setState({textString: event.target.value});
    }

    buttonClick: function(){
        this.props.sendData(this.state.textString);
    }

    render: function(){
        <div>
        <input type="text" value={this.state.textString} 
               onChange={this.textChange}/>
        <button onClick={this.buttonClick}
        </div>
    }

});

There are other ways of handling data, and it might be worth your while creating a data store to store global variables and handle various events. In this way you would keep the data flow of your application one way. In smaller scale cases however, this solution should suffice.

0
votes

Use the eventBus to send/receive date from child/parent components respectively.

Example below:

class Date extends Component {

 constructor(props) {
    super(props);
    this.state = {
        date:'',           
}
   this.callback = this.callback.bind(this); // register callback method
}

callback(date){    // callback method to receive data
    this.setState({date: date});
}


componentDidMount(){
    EventBus.on("date", this.callback);
}
render() {

<div>
      {this.state.date}
</div>
  }
} 

From any other component

 handleDayClick(day) {
         EventBus.publish("date", day);
  }

https://github.com/arkency/event-bus