Reputation:
I have a React component with a form what I need to do is to catch the username and then save it using sessionstorage.
Here's is what I'm currently trying but it's not saving it.
Here's the code:
class Login extends Component {
constructor(props) {
super(props);
this.state = {
password: '',
redirect: false,
};
this.onUsernameChange = this.onUsernameChange.bind(this);
this.onPasswordChange = this.onPasswordChange.bind(this);
}
onUsernameChange(event) {
this.setState({ username: event.target.value });
}
onPasswordChange(event) {
this.setState({ password: event.target.value });
}
handleSubmit() {
event.preventDefault();
sessionStorage.setItem('username', this.username);
}
render() {
return (
<div>
<form className="form-signin" onSubmit={this.handleSubmit}>
<input type="text" value={this.username} onChange={this.onUsernameChange} />
<input type="password" value={this.password} onChange={this.onPasswordChange} />
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default Login;
How can I get this to work?
Upvotes: 1
Views: 2345
Reputation: 1227
handleSubmit(event) {
event.preventDefault();
// sessionStorage.setItem('username', this.username); your code
sessionStorage.setItem('username', this.state.username);
}
You have got username by using this.username. But there is no username in this. So you get username from component's state.
And your method has no arguments. If you want event you put event in argument.
Upvotes: 0
Reputation: 406
I think you just need to add username
to the state, and then pass event
to handleSubmit
class Login extends Component {
constructor(props) {
super(props);
this.state = {
password: '',
redirect: false,
username: ''
};
this.onUsernameChange = this.onUsernameChange.bind(this);
this.onPasswordChange = this.onPasswordChange.bind(this);
}
onUsernameChange(event) {
this.setState({ username: event.target.value });
}
onPasswordChange(event) {
this.setState({ password: event.target.value });
}
handleSubmit(event) {
event.preventDefault();
sessionStorage.setItem('username', this.state.username);
}
render() {
return (
<div>
<form className="form-signin" onSubmit={this.handleSubmit}>
<input type="text" value={this.username} onChange={this.onUsernameChange} />
<input type="password" value={this.password} onChange={this.onPasswordChange} />
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
export default Login;
Upvotes: 2