scrimba
React log in - log out
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

React log in - log out
by
AboutCommentsNotes
React log in - log out
by
Expand for more info
App.js
run
preview
console
import React, {Component} from 'react';

/*
Challenge:
Given a stateless functional component:
1. Follow the steps necessary to add state to it,
2. Have state keep track of whether the user is logged in or not
3. Add a button that logs the user in/out
a. extra challenge - make the button display "log in" if they're not logged in and "log out" if they are
4. Display text that says "Logged in" if the user is logged in, or "Logged out" if they're not.
*/

class App extends Component {
constructor() {
super();
this.state = {
isLogged: false
}
this.handleClick = this.handleClick.bind(this);
}

handleClick () {
this.setState(prevState => {
return {
isLogged: !prevState.isLogged
}
})
// (this.state.isLogged !== true) ? ({isLogged: true}) :
// ({isLogged: false})

}

render() {
console.log(this.state.isLogged)
let buttonText = this.state.isLogged ? 'Log out' : 'Log in';
let displayText = this.state.isLogged ? 'logged in' : 'logged out';

return(
<div>
<h3>You`re {displayText}</h3>
<button onClick={this.handleClick}>{buttonText}</button>
</div>
)
}
}

export default App;
Console
false
,
true
,
false
,
true
,
/index.html
LIVE