I want to render digital clock on the browser , i don’t know where to use setInterval() function in my script and also the what will be the name of function used as a first argument.
JavaScript
x
44
44
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<title>My First App</title>
5
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
6
</head>
7
<body>
8
<div id="react-app"></div>
9
<div id="clock-box"></div>
10
11
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
12
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>
13
14
<script type="text/jsx">
15
16
class StoryBox extends React.Component{
17
render(){
18
return(<div> Hello World </div> );
19
}
20
}
21
var target= document.getElementById('react-app');
22
var clockTarget=document.getElementById('clock-box');
23
ReactDOM.render(<StoryBox/>,target)
24
25
class ClockFunction extends React.Component{
26
render(){
27
return(<div>
28
<h1>Digital Clock</h1>
29
<h2>
30
{
31
new Date().toLocaleTimeString()
32
}
33
</h2>
34
</div>) ;
35
}
36
}
37
38
ReactDOM.render(<ClockFunction />,clockTarget);
39
40
</script>
41
42
</body>
43
</html>
44
Advertisement
Answer
For this you’re going to need a few things:
- a
setInterval
to update the time - a variable in the component’s
state
for keeping track of the time - a safe way of adding and removing the
setInterval
when the component mounts and unmounts respectively
This component will do all of those things:
JavaScript
1
30
30
1
class ClockFunction extends React.Component {
2
3
constructor() {
4
super();
5
this.state = { time: new Date() }; // initialise the state
6
}
7
8
componentDidMount() { // create the interval once component is mounted
9
this.update = setInterval(() => {
10
this.setState({ time: new Date() });
11
}, 1 * 1000); // every 1 seconds
12
}
13
14
componentWillUnmount() { // delete the interval just before component is removed
15
clearInterval(this.update);
16
}
17
18
render() {
19
const { time } = this.state; // retrieve the time from state
20
21
return (<div>
22
<h1>Digital Clock</h1>
23
<h2>
24
{/* print the string prettily */}
25
{time.toLocaleTimeString()}
26
</h2>
27
</div>);
28
}
29
}
30