ksingh
ksingh

Reputation: 163

Why does React update state onChange but not onSubmit (input)?

See the code below:

App.jsx

addTodo = event => {
    this.setState({
      newTodo: event.target.value,
      todos: [...this.state.todos, this.state.newTodo]
    });

    console.log(this.state.todos);
  };

AddTodo.jsx

        <form onSubmit={this.props.preventDefault} className="ui form">
          <div className="field">
            <label>Add a todo here:</label>
            <input
              onChange={this.props.addTodo} // addTodo works for onChange why not onSubmit?
              type="text"
              placeholder="Walk the dog..."></input>
            <button type="submit">Submit</button>
          </div>
        </form>

The function updates the state as expected for onChange but nothing for onSubmit, why is this? I suspect it has something to do with the tag it's on (input not form).

Upvotes: 0

Views: 1120

Answers (1)

Nick Kinlen
Nick Kinlen

Reputation: 1404

preventDefault prevents the form from carrying out it's default action i.e. submitting the form. Check out the MDN documentation for preventDefault.

You need to write a custom function that handles what you want the form to do and set onSubmit equal to that function. Inside that custom function you can use event.preventDefault to prevent the form from initially carrying out it's default action. Then, later in that function, you can write whatever code you need to do whatever it is you're trying to do.

Here is an example from the React docs:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Also, check out the React docs for uncontrolled components and understand the difference between the example I showed above (controlled component approach) and the uncontrolled component approach.

Upvotes: 2

Related Questions