iscream
iscream

Reputation: 790

onSubmit event handler not working in Reactjs form

I am new to react and have this form:

class CustomForm extends React.Component {

    handleFormSubmit = (e) => {
        e.preventDefault();
        const title = e.target.elements.title.value;
        const content = e.target.elements.content.value;
        console.log(title, content)
    }

    render() {
        return (
            <div>
                <Form onSubmit={ this.handleFormSubmit }>
                    <FormItem label='Title'>
                        <Input name='title' placeholder='Put a title here' />
                    </FormItem>
                    <FormItem label='Content'>
                        <Input name='content' placeholder='Enter some content' />
                    </FormItem>
                    <FormItem>
                        <Button type='primary' htmlType='submit'>Submit</Button>
                    </FormItem>
                </Form>
            </div>
        )
    }
}

The form is not submitting anything/nothing in console log. I tried it with onSubmitCapture and that seems to work. How do I fix this?

Upvotes: 0

Views: 4456

Answers (3)

Sahil Sharma
Sahil Sharma

Reputation: 1899

You need to bind the event handlers in the constructor in order to work. Read more here https://reactjs.org/docs/handling-events.html:

class CustomForm extends React.Component {    
    constructor(props) {
     super(props)

      this.handleFormSubmit = this.handleFormSubmit.bind(this)
     }

    handleFormSubmit = (e) => {
        e.preventDefault();
        const title = e.target.elements.title.value;
        const content = e.target.elements.content.value;
        console.log(title, content)
    }

    render() {
        return (
            <div>
                <Form onSubmit={ this.handleFormSubmit }>
                    <FormItem label='Title'>
                        <Input name='title' placeholder='Put a title here' />
                    </FormItem>
                    <FormItem label='Content'>
                        <Input name='content' placeholder='Enter some content' />
                    </FormItem>
                    <FormItem>
                        <Button type='primary' htmlType='submit'>Submit</Button>
                    </FormItem>
                </Form>
            </div>
        )
    }
}

Upvotes: 0

Ashish
Ashish

Reputation: 4330

From your code it looks like you are using some custom component <Form>.. this is not the normal <form> because custom <Form> component might not have the prop onSubmit. Go through the documentation of the component you are using.

Upvotes: 2

Palash Gupta
Palash Gupta

Reputation: 390

button with type='submit' will trigger the form onSubmit Handler

Upvotes: 0

Related Questions