React basic clock example using setInterval

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=""></script>
<script src=""></script>
<script src=""></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>{}</div>);
  componentWillUnmount: function() {
ReactDOM.render(<MyComp/>, document.getElementById('mycomp') );
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments