joel_ace
joel_ace

Reputation: 133

Why does the logical AND operator call these two functions in this case

I have a react component class that contains two methods handleSubmit and handleReset.

class Filter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // initial state
    };

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

  handleReset() {
    this.setState({
      // reset state to initial state
    });
  }

  handleSubmit(event) {
    // handle form submission and sending request to api endpoint
  }

  render() {    
    return (
      <form className="form-horizontal col-sm-12" onSubmit={this.handleSubmit}>
        <OtherFormElements />
        <button
          type="submit"
          className="btn btn-success"
          onClick={this.handleSubmit && this.handleReset}
        >Submit
        </button>
      </form>
    );
  }
}

When the submit button is clicked, both functions are called. Though this is the desired result, from my own understanding of the logical AND operator, this is not supposed to be so. From my understanding, a && b will result to b if a evaluates to true. What I want to know is why are both functions called in this case?

Upvotes: 2

Views: 498

Answers (2)

Prakash Sharma
Prakash Sharma

Reputation: 16482

What I want to know is why are both functions called in this case?

Because onClick={this.handleSubmit && this.handleReset} evaluates to onClick={this.handleReset} making call to this.handleReset and you have onSubmit={this.handleSubmit} handler on form tag.

Therefore clicking on button calls both functions (i.e. one because of click handler and other because of form submit event).

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175098

That's because both the Form's onSubmit and the button's onClick are called.

It's easy to deduce what would be the onSubmit, it's set to this.handleSubmit.

The button's is this.handleSubmit && this.handleReset, the JavaScript && operator returns the first falsey operand, and if all of them are truthy, it retuns the last operand, which is this.handleReset.

As a result, this.handleReset is called when the button's click event is fired, followed by this.handleSubmit when the form's submit event is fired.

Upvotes: 4

Related Questions