dev_kishore dev_kishore - 1 month ago 22
React JSX Question

REDUX-FORM error on handleSubmit

I am getting error while using redux-form

Error msg in console:



  • bundle.js:32511 Uncaught Error: You must either pass handleSubmit()
    an onSubmit function or pass onSubmit as a prop(…)




the above error appeared on page load and button click

Please refer to the below code sample which cause the console error.



import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import { createPost } from '../actions/index';

class PostsNew extends Component {

render() {
const { fields: { title, categories, content }, handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.props.createPost)}>
<h3>Create a new Post</h3>

<div className="form-group">
<label>Title</label>
<input type="text" className="form-control" {...title}/>
</div>

<div className="form-group">
<label>Categories</label>
<input type="text" className="form-control" {...categories}/>
</div>

<div className="form-group">
<label>Content</label>
<textarea className="form-control" {...content}/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
);
}
}

export default reduxForm({
form: 'PostsNewForm',
fields: ['title', 'categories', 'content']
}, null, { createPost })(PostsNew);






This was a step by step follow of StephenGrider redux tutorial


Thanks in advance :)

Answer

If PostsNew is Container (if this is directly invoked form Routes) then you have to make handleSubmit function instead of taking from this.props

import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
import { createPost } from '../actions/index';

class PostsNew extends Component {

  handleSubmit(formValues){
    console.log(formValues);
    //do what ever you want
  }

  render() {
    const { fields: { title, categories, content } } = this.props;
    return (
      <form onSubmit={this.handleSubmit(this.props.createPost)}>
        <h3>Create a new Post</h3>

        <div className="form-group">
          <label>Title</label>
          <input type="text" className="form-control" {...title}/>
        </div>

        <div className="form-group">
          <label>Categories</label>
          <input type="text" className="form-control" {...categories}/>
        </div>

        <div className="form-group">
          <label>Content</label>
          <textarea className="form-control" {...content}/>
        </div>
        <button type="submit" className="btn btn-primary">Submit</button>
      </form>
    );
  }
}

OR
In case PostsNew is React Component that is used inside a Container then you can pass handleSubmit in props of PostsNew

<PostsNew
 handleSubmit={ (values) => {console.log(values)}}
/>