React ChessTimer

Simulate a Chess Timer

by vikikamath

HTML

<script src="https://fbcdn-dragon-a.akamaihd.net/hphotos-ak-xta1/t39.3284-6/12056959_1183410128340718_1702703460_n.js"></script>
<div id="main">

</div>

Babel + JSX

var initduration = 60;
var ChessTimer = React.createClass({
  getInitialState: function() {
    return {wseconds: this.props.startWith, bseconds: this.props.startWith, color: 'WHITE', interval: undefined, start_reset: {buttonText: 'START', handler: this.start}};
  },
  componentDidMount: function() {
  	//this.setState({start_reset: {buttonText: 'START', handler: this.start}});
  },
  start: function() {
  	this.setState({start_reset: {buttonText: 'RESET', handler: this.reset}});
  	this.state.interval = setInterval(this.tick, 1000);
  }, 
  tick: function() {
  	if(this.state.color === 'WHITE'){
    		if (this.state.wseconds > 0){
          this.setState({wseconds: this.state.wseconds - 1})
        } else{
        	clearInterval.call(null, this.state.interval);
        }
    } else{
    		console.log('booo');
    		if (this.state.bseconds > 0){
        	this.setState({bseconds: this.state.bseconds - 1});
        } else{
        	clearInterval.call(null, this.state.interval);
        }
    }
  },
  switch: function() {
    this.setState({color: this.state.color === 'WHITE' ? 'BLACK' : 'WHITE'});
  },
  reset: function() {
  	clearInterval.call(null, this.state.interval);
  	this.setState({wseconds: initduration(), bseconds: initduration(), color: 'WHITE', start_reset: {buttonText: 'START', handler: this.start} });
  },
  render: function() {
    return (
    	<div>
      <p>
        White has {this.state.wseconds} seconds remaining.
      </p>
      <p>
        Black has {this.state.bseconds} seconds remaining.
      </p>
      <button onClick={this.switch}>SWITCH</button>
      <button onClick={this.state.start_reset.handler}>{this.state.start_reset.buttonText}</button>
      </div>
    );
  }
});

var ControlBar = React.createClass({
	
  getInitialState: function() {
  	return {
    	buttons: [{
      	text: 'SWITCH',
        handler: 'switch',
        enabled: false
      }, {
      	text: 'RESET',
        handler: 'reset',
        enabled: false
      },{
   ...