Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass form data to parent class in react

Tags:

reactjs

I have following react classes:

var FormBox = React.createClass({
    render: function() {
        return (
            <h1>Forms:</h1>
            <InternalForm name="foo" />
            <InternalForm name="bar" />
            <form className="externalForm" onSubmit={this.handleSubmit}>
                <input type="submit" value="Post" /> 
            </form>
        );
  }
})
var InternalForm = React.createClass({
    render: function() {
        return (
            <h1>{this.props.name}</h1>
            <form className="internalForm">
                <input type="text"/>
                /* form strucure based on props*/
            </form>
    );
  }
})

After external form submition, I need to get a json that contains values of intertal forms like

{'foo':{},'bar':{}}

I guess that FormBox needs to call onSubmit on each internal form, but it doesn't feel quite right.

How to perform it? Thanks

like image 867
foo Avatar asked Nov 23 '15 09:11

foo


1 Answers

You are right, calling onSubmit on each Subcomponent is not the way you would do this in react. Instead of this, you should hold a state object in your external containing the values of foo and bar. To keep them in sync, you should pass a callback to the child forms so they update the state when needed. Then when submitting you only need to use the external form's state.

Something like this:

var FormBox = React.createClass({
    getInitialState: function() {
      return {
        foo: null,
        var: null
      };  
    },
  
    onChildChange: function(childName, childValue){
      let newState = {};
      newState[childName] = childValue;
      this.setState(newState)
    },
  
    render: function() {
        return (
            <h1>Forms:</h1>
            <InternalForm name="foo" onFormChange={this.onChildChange}/>
            <InternalForm name="bar" onFormChange={this.onChildChange} />
            <form className="externalForm" onSubmit={this.handleSubmit} onChange={this.onChildChange.bind(this, 'bar')}>
                <input type="submit" value="Post" /> 
            </form>
        );
  }
})
var InternalForm = React.createClass({
    onFormChange: function(e) {
        this.props.onFormChange(this.props.name, e.target.value);
    }
  
    render: function() {
        return (
            <h1>{this.props.name}</h1>
            <form className="internalForm">
                <input type="text" onChange={this.onFormChange}/>
                /* form strucure based on props*/
            </form>
    );
  }
})
like image 193
Emilio Rodriguez Avatar answered Oct 14 '22 07:10

Emilio Rodriguez