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.
<!DOCTYPE html> <html> <head> <title>My First App</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script> </head> <body> <div id="react-app"></div> <div id="clock-box"></div> <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script> <script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script> <script type="text/jsx"> class StoryBox extends React.Component{ render(){ return(<div> Hello World </div> ); } } var target= document.getElementById('react-app'); var clockTarget=document.getElementById('clock-box'); ReactDOM.render(<StoryBox/>,target) class ClockFunction extends React.Component{ render(){ return(<div> <h1>Digital Clock</h1> <h2> { new Date().toLocaleTimeString() } </h2> </div>) ; } } ReactDOM.render(<ClockFunction />,clockTarget); </script> </body> </html>
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:
class ClockFunction extends React.Component { constructor() { super(); this.state = { time: new Date() }; // initialise the state } componentDidMount() { // create the interval once component is mounted this.update = setInterval(() => { this.setState({ time: new Date() }); }, 1 * 1000); // every 1 seconds } componentWillUnmount() { // delete the interval just before component is removed clearInterval(this.update); } render() { const { time } = this.state; // retrieve the time from state return (<div> <h1>Digital Clock</h1> <h2> {/* print the string prettily */} {time.toLocaleTimeString()} </h2> </div>); } }