Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  14] [ 5]  / answers: 1 / hits: 19154  / 9 Years ago, tue, november 10, 2015, 12:00:00

I have a LoginForm component. I want to check before submit, that both loginName and password is set. I tried with this code (a lot of stuff omitted):



class LoginForm extends Component {

constructor() {
super();

this.state = {
error: ,

loginName: ,
password: ,
remember: true
};
}


submit(e) {
e.preventDefault();
if(!this.state.loginName || !this.state.password) { //this is null
this.setState({ error: Fill in both fields });
} else {
console.log(submitting form);
}
}

render() {
return (
<div className=col-xs-12 col-sm-6 col-md-4>
<form className=login onSubmit={this.submit}>
<button type=submit className=btn btn-default>Sign in</button>
</form>
</div>
);
}
}

export default LoginForm;


however, i get a TypeError in the event handler, saying that this is null.



What should I be doing?


More From » reactjs

 Answers
308

You need set this for submit method because now this is undefined, for this operation you can use .bind



onSubmit={ this.submit.bind(this) }


Example



or you can use arrow function



onSubmit={ (e) => this.submit(e) }


Example


[#64450] Saturday, November 7, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnyblaynes

Total Points: 667
Total Questions: 121
Total Answers: 102

Location: Anguilla
Member since Sat, Jan 23, 2021
3 Years ago
;