0

I am trying to create a new Login component using Material-ui. I have two state variables 'username' and 'password'. When I fill textfields and submit it, the state values are not available inside my submitForm function.

My code is:

class Login extends React.Component {

constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
    };
  }


submitForm(e) {
  e.preventDefault();
   console.log('test');
   console.log(this.state.username.trim());
   console.log(this.state.password.trim());

  };

render() {

    return (
     <form className="commentForm">
    <TextField
      value={this.state.username}
      onChange={e => this.setState({ username: e.target.value })}
      hintText = "username" style={textfieldStyles.margin}

    />
    <TextField
      value={this.state.password}
      onChange={e => this.setState({ password: e.target.value })}
      hintText = "password" type="password"

    />
         <IconButton iconStyle={{iconHoverColor: '#55ff55'}}
     tooltip="Sing In" key='signin-button' 
     // onTouchTap={this.handleTouchTap}
     onClick={this.submitForm}
     >
    <ArrowIcon color={Colors.cyan500} style={{marginTop: 30}} hoverColor={hoverColor} />
    </IconButton>
  </form>
    );
  }
}

export default Login;

The console output console.log('test'); is working but

console.log(this.state.username.trim());
console.log(this.state.password.trim());

not giving any output.

Did I miss something to set state variables? or I need to include other things to make it working?

1 Answer 1

1

Because you're using ES6 class syntax, you should be binding this for your class methods, in this case your submitForm method.

https://facebook.github.io/react/docs/reusable-components.html#no-autobinding

constructor(props) {
  super(props);
  this.submitForm = this.submitForm.bind(this);
  ...
}

Otherwise you won't be able to access this.state inside submitForm.

Sign up to request clarification or add additional context in comments.

2 Comments

I think this is the best way. I used <IconButton iconStyle={{iconHoverColor: '#55ff55'}} tooltip="Sing In" key='signin-button' // onTouchTap={this.handleTouchTap} onClick={this.submitForm.bind(this)} > I bind the component while clicking the button as 'this.submitForm.bind(this)'. But I think this is a hard way. Thanks.
Binding during the render execution is not good for performance

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.