Im using React and I need an event for when the user logs in. What is the recommended way to do this?
I found this thread but its a few years old and also not React specific, does it still contain the best approaches?
Im using React and I need an event for when the user logs in. What is the recommended way to do this?
I found this thread but its a few years old and also not React specific, does it still contain the best approaches?
Hi - I don’t know about the recommended way, but this is roughly how I do it.
/* LoginForm.jx */
import React from ‘react’ ;
import prebind from ‘meteor-react-prebind’ ;
/* called by NotLoggedIn.jsx */
export default class LoginForm extends React.Component {
constructor( props ) {
super( props ) ;
prebind( this ) ;
this.state = {
user: "",
pass: "",
} ;
}
componentDidMount() {
this.refs.usernminput.focus() ;
}
handleLogin( input, evnt ) {
if ( input == "user" ) {
this.setState({
user: evnt.target.value
})
this.props.userChanged( evnt.target.value ) ;
} ;
if ( input == "pass" ) {
this.setState({
pass: evnt.target.value
})
this.props.passChanged( evnt.target.value ) ;
}
}
render() {
let user = this.state.user ; // login
let pass = this.state.pass ;
return (
<div>
<p className="senter-text phont14">
<b>Click the "X" above to close this form and display other options.</b>
</p>
<div className="loginform">
<strong>
<div className="list">
<label className="item item-input">
<span className="input-label"><b className="phont20">Username</b></span>
<input ref="usernminput" value={ user } type="text"
onChange={ this.handleLogin.bind( this, "user" ) } />
</label>
<label className="item item-input">
<span className="input-label"><b className="phont20">Password</b></span>
<input value={ pass } type="password" onChange={ this.handleLogin.bind(
this, "pass" ) } />
</label>
</div>
<div className="login-button text-center">
{ /* this.props.login is from Profile, the login fn is in NotLoggedIn */ }
<button onClick={ this.props.login.bind( null, this.state.user, this.state.pass ) }
className="button button-outline button-assertive">
<b className="phont20">Log Me In</b>
</button>
</div>
</strong>
<hr/>
<div>
Then in NotLoggedIn component (the parent of the LoginForm component above), it has the login() function something like:
login() {
let that = this ;
if ( this.state.user && this.state.pass ) {
Meteor.loginWithPassword( this.state.user, this.state.pass, function( error ) {
if ( error ) {
that.setState( { user: "" } ) ;
that.setState( { pass: "" } ) ;
alert( "There was a login error. The error is ** " + error.message + " **." ) ;
return false ;
} else {
// whatever
}
that.props.nowLoggedIn( true ) ;
return true ;
}
}) ;
–ciao, jw