Skip to content

Instantly share code, notes, and snippets.

@soska
Created May 6, 2015 21:44
Show Gist options
  • Save soska/0f260c3ec0aa83ba10fe to your computer and use it in GitHub Desktop.
Save soska/0f260c3ec0aa83ba10fe to your computer and use it in GitHub Desktop.
Login React Component
const React = require('react');
const Login = React.createClass({
propTypes:{
username : React.PropTypes.string,
password : React.PropTypes.string,
startWithLogin : React.PropTypes.bool,
error : React.PropTypes.string,
onLogin : React.PropTypes.func,
onSignup : React.PropTypes.func,
},
getDefaultProps(){
return {
username : '',
password : '',
startWithLogin : true,
loginTitle : 'Please log in first',
signupTitle : 'Create an account',
loginSwitchText : 'I don\'t have an account',
signupSwitchText : 'I already have an account',
error : null
}
},
getInitialState(){
return ({
username : this.props.username,
password : this.props.password,
isLogin : this.props.startWithLogin,
})
},
switchMode(){
this.setState({
isLogin : !this.state.isLogin
})
},
onSubmit(e){
e.preventDefault();
let credentials = {
username : this.refs.username.getDOMNode().value,
password : this.refs.password.getDOMNode().value,
};
if (this.state.isLogin) {
this.props.onLogin(credentials);
}else{
this.props.onSignup(credentials);
}
},
renderTitle(){
return(
<h2>
{ this.state.isLogin ? this.props.loginTitle : this.props.signupTitle }
</h2>
);
},
renderError(){
if (!this.props.error) {
return null;
}
return(
<div className='alert alert-danger'>
{this.props.error}
</div>
);
},
renderMessage(){
console.log(this.state);
if (!this.props.message) {
return null;
}
return(
<div className='alert alert-warning'>
{this.props.message}
</div>
);
},
renderSwitchControl(){
return(
<div>
<a href='#' onClick={(e)=>{
e.preventDefault();
this.switchMode();
}}>
{ this.state.isLogin ? this.props.loginSwitchText : this.props.signupSwitchText }
</a>
</div>
);
},
render(){
let className = 'login-form login-form--' + (this.state.isLogin ? 'login' : 'signup');
return (
<div className={className}>
<form onSubmit={this.onSubmit}>
<div className="panel panel-default">
{this.renderTitle()}
{this.renderError()}
{this.renderMessage()}
<div className='form-group'>
<label htmlFor="username">Email</label>
<input type="email" ref='username' className='form-control' defaultValue={this.state.username} />
<label htmlFor="username">Password</label>
<input type="password" ref='password' className='form-control'/>
</div>
<button>{this.state.isLogin ? 'Log in' : 'Sign up'}</button>
<hr/>
{this.renderSwitchControl()}
</div>
</form>
</div>
);
}
})
module.exports = Login;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment