React event handling problem

import React from 'react';
import ReactDOM from 'react-dom';

class Contact extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      password: 'swordfish',
      authorized: false
    };
    this.authorize = this.authorize.bind(this);
  }

  authorize(e) {
    const password = e.target.querySelector(
      'input[type="password"]').value;
    const auth = password == this.state.password;
    this.setState({
      authorized: auth
    });
  }

  render() {
    const login = (
      <form action='#' onSubmit={this.authorize}>
       <input type ="password" placeholder="placeholder" />
       <input type ="submit" />
      </form>
      )

    let contactInfo =(
      <ul>
          <li>
            client@example.com
          </li>
          <li>
            555.555.5555
          </li>
        </ul>

    );
    
    return (
      <div id="authorization">
    <h1>
  { this.state.authorized ? 'Contact' : 'Enter the Password' }
</h1>
      { this.state.authorized ? contactInfo : login }
    
        
        
      </div>
    );
  }
}

ReactDOM.render(
  <Contact />, 
  document.getElementById('app')
);

When adding event onSubmit why {this.authorize()) does’t work whereas onSubmit={this.authorize}> work

Hello, and welcome to the forums!

The reason is that when you use this.authorize(), you are calling the method immediately and using it’s return value. This means that when onSubmit is triggered, instead of being able to call the method itself, it uses the value returned by the call to this.authorize(), which is undefined since the method doesn’t return anything.

Consider the following non-React example:

const test = () => {
    console.log('test function was run!');
}

console.log('test() =', test());
// Outputs:
// test function was run!
// test() = undefined

console.log('test =', test);
// Outputs:
// test = [Function: test]

Notice it remained a function when the parenthesis were omitted and the function itself wasn’t called.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.