I am currently doing a simple to-do list, and I have a problem that when I click enter, my web will reload, which I expect will be adding a new task.
Thank you for helping.
handleSubmit = (event) => {
event.preventDefault();
if (!this.state.input) {
alert("You need to write a task!");
return;
}
this.props.addNewTask({
id: Math.floor(Math.random() * 1000 + 1),
value: this.state.input,
});
this.setState({ showAddTask: false, input: "" });
};
handleKeyDown = (event) => {
event.preventDefault();
if (event.key === "Enter") {
this.handleSubmit(event);
}
};
render() {
return (
<div className="main-add-task">
{this.state.showAddTask ? (
<form className="add-task-form">
<input
type="text"
placeholder="Do homework at 3pm"
onChange={this.handleChangeInput}
autoFocus
/>
<div className="change-button">
<button type="button" onClick={this.handleCancel}>
Cancel
</button>
<button type="button" onClick={this.handleSubmit}>
Add task
</button>
</div>
</form>
) : (
<button onClick={this.handleShow}>Add Task</button>
)}
</div>
);
}
}
export default AddTask;
i tried to add event.preventDefault();to my 2 functions
1 Answer 1
The main problem in this code is the handleKeyDown method.
You're currently using event.preventDefault(), which prevents default submissions when the Enter key is pressed. Then you're calling the handleSubmit() function.
A better way to handle form submissions can be:
handleSubmit = (event) => {
// Prevent default form submission (page reload) whic you're already doing
event.preventDefault();
if (!this.state.input) {
alert("You need to write a task!");
return;
}
this.props.addNewTask({
id: Math.floor(Math.random() * 1000 + 1),
value: this.state.input,
});
this.setState({ showAddTask: false, input: "" });
};
render() {
return (
<div className="main-add-task">
{this.state.showAddTask ? (
<form
className="add-task-form"
onSubmit={this.handleSubmit} // Add this line
>
<input
type="text"
placeholder="Do homework at 3pm"
onChange={this.handleChangeInput}
value={this.state.input} // add this to make it a controlled component
autoFocus
/>
<div className="change-button">
<button type="button" onClick={this.handleCancel}>
Cancel
</button>
<button type="submit"> {/* change to type="submit" */}
Add task
</button>
</div>
</form>
) : (
<button onClick={this.handleShow}>Add Task</button>
)}
</div>
);
}
Another update I would look into is using hooks (useState / etc). class based / this.X --- can become confusing from my point of view
Comments
Explore related questions
See similar questions with these tags.
onSubmitprop of your<form/>element. The button with"type="submit"will automatically submit the form, calling that function. Then theevent.preventDefault();will work, cos the event is coming from the form itself