Swapnil Bhikule
Swapnil Bhikule

Reputation: 606

Passing data to parent component in react

I've created on form in child component. After submitting that form using jquery ajax method ($.ajax) I am retriving some data in json format. I want to put that data in my parent component's state. So, is there any method in react.js for passing value or data from child component to its parent component?

Thank you..

Upvotes: 4

Views: 3365

Answers (1)

pmilla1606
pmilla1606

Reputation: 755

The way to do this without some kind of Flux implementation is to create a function on the parent element that handles the response/data from the child and pass that function as a prop. Then call that function from the child. Something like this:

Parent:

handleResponse(data) {
  console.log(data)
}

render() {
  return(
    <div>
      <Child handleResponse={this.handleResponse} />
    </div>
  );
}

then in the child:

handleAjax() {
  $.get(url).then( (response) => {
    this.props.handleResponse(response)
  });
}

this all assumes ES6 syntax. Using ES5 you're going to have to use bind or var that = this to scope everything correctly.

Upvotes: 11

Related Questions