Skip to content

Instantly share code, notes, and snippets.

@Blake-C
Last active June 12, 2019 05:37
Show Gist options
  • Select an option

  • Save Blake-C/04451c0d546c423575b6f58bb4af2a64 to your computer and use it in GitHub Desktop.

Select an option

Save Blake-C/04451c0d546c423575b6f58bb4af2a64 to your computer and use it in GitHub Desktop.
Conditional Rendering - React
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(props) {
super(props)
this.state = {
loggedIn: false
}
this.onClickHandler = this.onClickHandler.bind(this)
}
onClickHandler() {
this.setState(prevState => {
return {
loggedIn: !prevState.loggedIn
}
})
}
render() {
return (
<div>
<button onClick={this.onClickHandler}>
{ this.state.loggedIn ? 'Log Out' : 'Log In' }
</button>
<h1>{ this.state.loggedIn ? 'Hello' : 'You must log in' }</h1>
</div>
)
}
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment