bnqtoan
bnqtoan

Reputation: 799

How can I handle redux form submission in child component?

In all examples that I read, we always handle submission of the form from parent component.

For instance:

export default class ParentComponent extends React.Component{
constructor(){
    super();
    this.state = {
        working: false,
        users: []
    }
}
handleSubmit(values){
    //do something
}
render(){
    return(
        <div className="container">
            <ReduxForm onSubmit={this.handleSubmit.bind(this)} {...this.props}/>
        </div>
    );
}
}

and in child component

class ReduxForm extends React.Component{
constructor(){
    super();
}
render(){
    const {handleSubmit, pristine, reset, submitting } = this.props;
    return(
        <div>
            <h2>Hello, Redux form</h2>
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="firstName">First Name</label>
                    <Field name="firstName" component="input" type="text" className="form-control"/>
                </div>
                <div className="form-group">
                    <label htmlFor="lastName">Last Name</label>
                    <Field name="lastName" component="input" type="text" className="form-control"/>
                </div>
                <div className="form-group">
                    <button type="submit" className="btn btn-success">Submit</button>
                </div>
            </form>
        </div>
    );
}
}

I think we should handle the submission in ReduxForm (child component) for reusable (what if we have another page, use that form again and we have to handle submission every time?)

I tried to handle the submission in redux form way, but it's not success.

Any idea?

Thank you so much!

Upvotes: 1

Views: 867

Answers (1)

Freez
Freez

Reputation: 7588

You can delegate the submission callback to the function of your choice

class ReduxForm extends React.Component{
   constructor(){
      super();
      this.submit = this.submit.bind(this);
   }
   submit(values) {
      alert('SUBMIT : ' + JSON.stringify(values));
   }
   render(){
      const { handleSubmit } = this.props;
      return ( 
         <form onSubmit={handleSubmit(this.submit)}>
         //                           ^^^^^^^^^^^
         //                           Your submission handler
         // ...
         </form>
   }
}

Upvotes: 4

Related Questions