I'm building a simple user search app using React and TypeScript. I have a basic form with an input text box to search users and an input button that submits the search. But the e.preventDefault()
method in my onSubmit
method doesn't seem to be working. When I submit, the whole app refreshes. Actually, it may be that onSubmit
isn't even being called at all.
private handleSubmit = (e: React.FormEvent<HTMLInputElement>) => {
e.preventDefault();
this.props.searchUsers(this.state.text);
this.setState({text: ''});
}
private handleChange = (e: React.FormEvent<HTMLInputElement>) => {
this.setState({text: e.currentTarget.value});
}
public render() {
return (
<div>
<form className="form">
<input
type="text"
name="text"
value={this.state.text}
placeholder="Search Users..."
onChange={this.handleChange}
/>
<input
type="submit"
value="search"
className="btn btn-dark btn-block"
onSubmit={this.handleSubmit}
/>
</form>
</div>
);
}
Any suggestions? Thanks!
You are adding onSubmit
in the wrong place.
You should add in the form
not in the button.
public render() {
return (
<div> // \/ added here
<form className="form" onSubmit={this.handleSubmit}>
<input
type="text"
name="text"
value={this.state.text}
placeholder="Search Users..."
onChange={this.handleChange}
/>
<input // removed from the button
type="submit"
value="search"
className="btn btn-dark btn-block"
/>
</form>
</div>
);
}
If you look at the example on the docs you will see that they add it in the form
.
*Remember that to trigger the form
's onSubmit
, your input
/button
needs to have type="submit"
You can simply do this :-
private handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
this.props.searchUsers(this.state.text);
this.setState({text: ''});
}
private handleChange = (e: React.FormEvent<HTMLInputElement>) => {
this.setState({text: e.currentTarget.value});
}
public render() {
return (
<div>
<form className="form" onSubmit={(e) =>this.handleSubmit(e)}>
<input
type="text"
name="text"
value={this.state.text}
placeholder="Search Users..."
onChange={this.handleChange}
/>
<input
type="submit"
value="search"
className="btn btn-dark btn-block"
/>
</form>
</div>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With