Created
October 22, 2019 09:12
-
-
Save react-ram/9ebb29215ce91447396deaa832507bf9 to your computer and use it in GitHub Desktop.
basics - conditonal rendering example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
isLoggedin: false | |
}; | |
this.handleLogin = this.handleLogin.bind(this); | |
this.handleLogout = this.handleLogout.bind(this); | |
} | |
handleLogout() { | |
this.setState({ | |
isLoggedin: false | |
}); | |
} | |
handleLogin() { | |
this.setState({ | |
isLoggedin: true | |
}); | |
} | |
render() { | |
let button; | |
if (this.state.isLoggedin) { | |
button = <LogoutButton onClick={this.handleLogout} />; | |
} else { | |
button = <LoginButton onClick={this.handleLogin} />; | |
} | |
return ( | |
<div> | |
<Greeting isLoggedin={this.state.isLoggedin} /> | |
{button} | |
</div> | |
); | |
} | |
} | |
function UserGreeting(props) { | |
return <h1>welcome back!</h1>; | |
} | |
function GuestGreeting(props) { | |
return <h1>GuestGreeting</h1>; | |
} | |
function Greeting(props) { | |
const isLoggedin = props.isLoggedin; | |
if (isLoggedin) return <UserGreeting />; | |
else return <GuestGreeting />; | |
} | |
function LoginButton(props) { | |
return <button onClick={props.onClick}>Login</button>; | |
} | |
function LogoutButton(props) { | |
return <button onClick={props.onClick}>Logout</button>; | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment