-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconditional-greeting.htm
More file actions
118 lines (102 loc) · 2.57 KB
/
Copy pathconditional-greeting.htm
File metadata and controls
118 lines (102 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Conditional Greeting</title>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
<script type="text/jsx">
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>
);
}
}
// This shows conditionally rendering elements
// Can conditionally render one element: put multiple ones into a div
// Example also shows how to transform array to list rendering using map()
function Mailbox(props) {
const unreadMessages = props.unreadMessages.map((subj, i) => <li key={i}>{subj}</li>);
return (
<div>
{props.unreadMessages.length > 0 &&
<div>
<h2>
You have {props.unreadMessages.length} unread messages.
</h2>
<ul>{unreadMessages}</ul>
{/* We can also inline the map() call:
<ul>props.unreadMessages.map((subj, i) => <li key={i}>{subj}</li>)</ul>
*/}
</div>
}
</div>
);
}
function UserGreeting(props) {
const messages = ['React', 'Re: React', 'Re:Re: React'];
return (
<div>
<h1>Welcome back!</h1>
<Mailbox unreadMessages={messages} />
</div>
);
}
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')
);
</script>
</body>
</html>