Scott Glascott
Scott Glascott

Reputation: 637

React form triggers button onClick with every input

I am trying to create a form which has two inputs and a button. When you click the button, the input fields are used to update the state and then show an alert with the information saved in the state. Currently, I have the inputs changing the state but its calling the alert function every time a letter is added to the input...

handleSubmit= (e) =>{
    alert(JSON.stringify(this.state, null, '  '));
  }

  render() {
    return (
      <div className="App">

            <label>
              Username:
              <input
              type="text"
              name="username"
              placeholder="username"
              value={this.state.username}
              onChange={e => this.setState({ username: e.target.value })}
            />
            </label>
            <label>
              Password:
              <input
              type="text"
              name="password"
              placeholder="password"
              value={this.state.password}
              onChange={e => this.setState({ password: e.target.value })}
            />
            </label>

            <button onClick={this.handleSubmit()}>Submit</button>
            <p>{this.state.token}</p>
          <WelcomeStory></WelcomeStory>
      </div>
    );
  };

Thank you, this is my first front end framework so it has been a big learning curve.

Upvotes: 4

Views: 2166

Answers (1)

Nick
Nick

Reputation: 1422

You do not want the function being called right away, but rather only when the button is clicked. onClick is an event listener waiting for the button to be clicked before calling this.handleSubmit. By having parenthesis, it will call the handleSubmit function as soon as the component is rendered. There are similar questions on SO where people go into it at greater detail if you would like to understand when you should use parenthesis and when you shouldn't: here and here.

<button onClick={this.handleSubmit}>Submit</button>

Upvotes: 3

Related Questions