Created
February 26, 2017 01:38
-
-
Save jwill9999/7430a7c90efeafc9164f8eba374b6ae2 to your computer and use it in GitHub Desktop.
React Conditional Rendering
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
render() { | |
const isLoggedIn = this.state.isLoggedIn; | |
return ( | |
<div> | |
The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in. | |
</div> | |
); | |
} |
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
class LoginControl extends React.Component { | |
constructor(props) { | |
super(props); | |
this.handleLoginClick = this.handleLoginClick.bind(this); | |
this.handleLogoutClick = this.handleLogoutClick.bind(this); | |
this.state = {isLoggedIn: false}; | |
} | |
handleLoginClick() { | |
this.setState({isLoggedIn: true}); | |
} | |
handleLogoutClick() { | |
this.setState({isLoggedIn: false}); | |
} | |
render() { | |
const isLoggedIn = this.state.isLoggedIn; | |
let button = null; | |
if (isLoggedIn) { | |
button = <LogoutButton onClick={this.handleLogoutClick} />; | |
} else { | |
button = <LoginButton onClick={this.handleLoginClick} />; | |
} | |
return ( | |
<div> | |
<Greeting isLoggedIn={isLoggedIn} /> | |
{button} | |
</div> | |
); | |
} | |
} | |
function UserGreeting(props) { | |
return <h1>Welcome back!</h1>; | |
} | |
function GuestGreeting(props) { | |
return <h1>Please sign up.</h1>; | |
} | |
function Greeting(props) { | |
const isLoggedIn = props.isLoggedIn; | |
if (isLoggedIn) { | |
return <UserGreeting />; | |
} | |
return <GuestGreeting />; | |
} | |
function LoginButton(props) { | |
return ( | |
<button onClick={props.onClick}> | |
Login | |
</button> | |
); | |
} | |
function LogoutButton(props) { | |
return ( | |
<button onClick={props.onClick}> | |
Logout | |
</button> | |
); | |
} | |
ReactDOM.render( | |
<LoginControl />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment