Skip to content

Instantly share code, notes, and snippets.

@react-ram
Created October 22, 2019 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save react-ram/9ebb29215ce91447396deaa832507bf9 to your computer and use it in GitHub Desktop.
Save react-ram/9ebb29215ce91447396deaa832507bf9 to your computer and use it in GitHub Desktop.
basics - conditonal rendering example
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