Sijan Bhandari
Sijan Bhandari

Reputation: 3051

Material-ui setting state values in form component not working

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?

Upvotes: 0

Views: 738

Answers (1)

slugo
slugo

Reputation: 1039

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.

Upvotes: 1

Related Questions