1

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.

Giala Jefferson
  • 1,809
  • 8
  • 20
  • 29
  • Possible duplicate of [How to pass data from child component to its parent in ReactJS?](http://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs) – Shubham Khatri Mar 21 '17 at 03:26
  • 1
    found a nice article about communication between react components https://www.ctheu.com/2015/02/12/how-to-communicate-between-react-components/#children-to-parent – imdzeeshan May 18 '17 at 20:54

2 Answers2

9

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.

morinx
  • 635
  • 7
  • 19
boyde712
  • 182
  • 1
  • 1
  • 5
0

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

Omer
  • 534
  • 7
  • 19