Reputation: 790
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
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
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
Reputation: 390
button with type='submit'
will trigger the form onSubmit
Handler
Upvotes: 0