Dinh Khoi Nguyen
Dinh Khoi Nguyen

Reputation: 3

How to Stop reloading the web when pressing enter in React

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

Upvotes: 0

Views: 48

Answers (1)

user19259811
user19259811

Reputation:

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

Upvotes: 1

Related Questions