I have the following React component:
class Form extends React.Component {
handleSubmit(e) {
e.preventDefault();
For me, it was because the form didn't have an action
property set.
<form onSubmit={this.handleSubmit} action="#">
<input placeholder="githug login" ref="login" />
<button>Add Login</button>
</form>
One obvious piece of information: do not forget to include your button inside the <form>
.
I got stuck for a while until I figured out I had put my submit button outside my form, like this:
<form onSubmit={ this.handleSubmit }>
<input placeholder="githug login" ref="login" />
</form>
<button type="submit">Add Login</button>
hence the onSubmit event was not being called, and would never be.
When you use React
with ES2015 classes you should set this
to event handlers
class Form extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
let loginInput = this.refs.login;
this.props.addCard(loginInput.value);
loginInput.value = '';
}
render() {
return(
<form onSubmit={ this.handleSubmit }>
<input placeholder="githug login" ref="login" />
<button>Add Login</button>
</form>
);
}
}
Example
No Autobinding
Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.
You need to use button
or input
with type="submit"
<button type="submit">Submit</button>
Or
<input type="submit" value="Submit" />