Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data to parent component in react

Tags:

reactjs

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..

like image 539
Swapnil Bhikule Avatar asked Dec 19 '22 00:12

Swapnil Bhikule


1 Answers

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.

like image 94
pmilla1606 Avatar answered Dec 31 '22 03:12

pmilla1606