Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values from child components in React

Tags:

ajax

reactjs

So I am just starting to use React and am having trouble gathering the input values of inputs within a child component. Basically, I am creating different components for a large form I am making, then in the encompassing component, I want to collect all the values of inputs on the children in an object I am calling data, and then send that collected input into a POST AJAX request (you can see an example in the last component I made). I can pull the values easily enough when I am inside of the components, but pulling them from the parent component I haven't figured out.

Thanks in advance. Just going through the pains right now with React so any recommendations on how to structure this better as well, I am all ears!

Here are my components:

Component one

var StepOne = React.createClass({
  getInitialState: function() {
    return {title: '', address: '', location: ''};
  },
  titleChange: function(e) {
    this.setState({title: e.target.value});
  },
  addressChange: function(e) {
   this.setState({address: e.target.value});
  },
  locationChange: function(e) {
    this.setState({location: e.target.value});
  },
  render: function() {
    return (
      <div className="stepOne">
        <ul>
          <li>
            <label>Title</label>
            <input type="text" value={this.state.title} onChange={this.titleChange} />
          </li>
          <li>
            <label>Address</label>
            <input type="text" value={this.state.address} onChange={this.addressChange} />
          </li>
          <li>
            <label>Location</label>
            <input id="location" type="text" value={this.state.location} onChange={this.locationChange} />
          </li>
        </ul>
      </div>
    );
  }, // render
}); // end of component

Component two

var StepTwo = React.createClass({
  getInitialState: function() {
    return {name: '', quantity: '', price: ''}
  },
  nameChange: function(e) {
    this.setState({name: e.target.value});
  },
  quantityChange: function(e) {
    this.setState({quantity: e.target.value});
  },
  priceChange: function(e) {
    this.setState({price: e.target.value});
  },
  render: function() {
    return (
      <div>
      <div className="name-section">
        <div className="add">
          <ul>
            <li>
              <label>Ticket Name</label>
              <input id="name" type="text" value={this.state.ticket_name} onChange={this.nameChange} />
            </li>
            <li>
              <label>Quantity Available</label>
              <input id="quantity" type="number" value={this.state.quantity} onChange={this.quantityChange} />
            </li>
            <li>
              <label>Price</label>
              <input id="price" type="number" value={this.state.price} onChange={this.priceChange} />
            </li>
          </ul>
        </div>
      </div>
      </div>
    );
  }
});

Final component to collect data and submit ajax request

EventCreation = React.createClass({
 getInitialState: function(){
  return {}
},
submit: function (e){
  var self

  e.preventDefault()
  self = this

  var data = {
    // I want to be able to collect the values into this object then send it in the ajax request. I thought this sort of thing would work below:
    title: this.state.title,
  }

  // Submit form via jQuery/AJAX
  $.ajax({
    type: 'POST',
    url: '/some/url',
    data: data
  })
  .done(function(data) {
    self.clearForm()
  })
  .fail(function(jqXhr) {
    console.log('failed to register');
  });
},
render: function() {
    return(
      <form>
        <StepOne />
        <StepTwo />
        // submit button here
      </form>
    );
  }
});
like image 613
luke Avatar asked Mar 04 '16 16:03

luke


People also ask

How do you get the value of a child component in a parent?

We can get child component values in the parent component by creating a reference to the child component using the @ref directive in the Parent component. Using the reference instance, you can access the child component values in the parent.

How do you get data from a component in React?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

How do you access child component variable in parent component React?

You may access the child state by passing a callback to the child component. Now if you click the button in the child component, you will execute the function passed from the parent and have access to the child component's state variables.

How do you pass props from child component to parent?

To pass data from a child component to its parent, we can call a parent function from the child component with arguments. The parent function can be passed down to the child as a prop, and the function arguments are the data that the parent will receive.


1 Answers

Define methods in the child components that return the data that you want and then in the parent component when you are rendering the children, define refs so later on when you want to retrieve the data that you need you can call those method on the children.

StepOne = React.createClass({
    getData: function() {
        return this.state;
    }
});

StepTwo = React.createClass({
    getData: function() {
        return this.state;
    }
});

EventCreation = React.createClass({
    submit: function() {
        var data = Object.assign(
            {},
            this._stepOne.getData(),
            this._stepTwo.getData()
        );

        // ... do AJAX
    },

    render: function() {
        return (
            <StepOne ref={(ref) => this._stepOne = ref} />
            <StepTwo ref={(ref) => this._stepTwo = ref} />
        );
    }
});
like image 60
Gaston Sanchez Avatar answered Sep 17 '22 02:09

Gaston Sanchez