React Example 1 - A simple timer.
Part of a tutorialzine article.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://fb.me/react-with-addons-0.14.7.js"></script>
<script src="https://fb.me/react-dom-0.14.7.min.js"></script>
<script >
</script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
CSS
* {
padding:0;
margin:0;
}
html{
font:14px normal Arial, sans-serif;
color:#626771;
}
body{
padding:60px;
text-align: center;
}
JavaScript 1.7
var TimerExample = React.createClass({
getInitialState: function(){
// This is called before our render function. The object that is
// returned is assigned to this.state, so we can use it later.
return { elapsed: 0 };
},
componentDidMount: function(){
// componentDidMount is called by react when the component
// has been rendered on the page. We can set the interval here:
this.timer = setInterval(this.tick, 50);
},
componentWillUnmount: function(){
// This method is called immediately before the component is removed
// from the page and destroyed. We can clear the interval here:
clearInterval(this.timer);
},
tick: function(){
// This function is called every 50 ms. It updates the
// elapsed counter. Calling setState causes the component to be re-rendered
this.setState({elapsed: new Date() - this.props.start});
},
render: function() {
var elapsed = Math.round(this.state.elapsed / 100);
// This will give a number with one digit after the decimal dot (xx.x):
var seconds = (elapsed / 10).toFixed(1);
// Although we return an entire <p> element, react will smartly update
// only the changed parts, which contain the seconds variable.
return <p>This example was started <b>{seconds} seconds</b> ago.</p>;
}
});
ReactDOM.render(
<TimerExample start={Date.now()} />,
document.getElementById('container')
);