To create a basic clock in React, we can use setInterval
in componentDidMount
and optionally clear it in componentWillUnmount
if relevant. You may also want to read React – Component Specs and Lifecycle. Here is the code snippet:
<script src="https://fb.me/react-0.14.7.js"></script> <script src="https://fb.me/react-dom-0.14.7.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script> <div id="mycomp"></div> <script type="text/babel"> var MyComp = React.createClass({ getInitialState: function(){ return {date: (new Date()).toLocaleTimeString()}; }, componentDidMount: function() { this.timerId = setInterval(this.update_time, 1000); }, update_time: function() { this.setState({date: (new Date()).toLocaleTimeString()}); }, render: function() { return (<div>{this.state.date}</div>); }, componentWillUnmount: function() { clearInterval(this.timerId); }, }); ReactDOM.render(<MyComp/>, document.getElementById('mycomp') ); </script>