-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclockupdate-stateful.htm
More file actions
60 lines (51 loc) · 1.34 KB
/
Copy pathclockupdate-stateful.htm
File metadata and controls
60 lines (51 loc) · 1.34 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>React Stateful Clock Update</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 Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
tick() {
this.setState({
date: new Date()
});
}
// When the Clock output is inserted in the DOM, React calls the componentDidMount() lifecycle hook.
// Inside it, the Clock component asks the browser to set up a timer to call tick() once a second.
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
// If the Clock component is ever removed from the DOM,
// React calls the componentWillUnmount() lifecycle hook so the timer is stopped.
componentWillUnmount() {
clearInterval(this.timerID);
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
</script>
</body>
</html>