Last active
August 29, 2016 17:56
-
-
Save Tmw/10008243 to your computer and use it in GitHub Desktop.
Poorly written calculator in React.js + JSX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title>Another React.js experiment (with JSX)</title> | |
<script src="http://fb.me/react-with-addons-0.10.0.js"></script> | |
<script src="http://fb.me/JSXTransformer-0.10.0.js"></script> | |
</head> | |
<body> | |
<script type="text/jsx"> | |
/** @jsx React.DOM */ | |
var Button = React.createClass({ | |
handleClick: function(){ | |
if(this.props.onMouseDown) | |
this.props.onMouseDown(this, this.props.value); | |
}, | |
render: function(){ | |
return <button onMouseDown={this.handleClick}>{this.props.value}</button> | |
} | |
}); | |
var KeyBoard = React.createClass({ | |
getInitialState: function(){ | |
return { | |
buttons: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "+", "-", "*", "/", "="] | |
}; | |
}, | |
onClickHandler: function(obj, val){ | |
if(val === "="){ | |
if(this.props.onCalculate) this.props.onCalculate(); | |
} | |
else{ | |
if(this.props.onKeyPress) this.props.onKeyPress(val); | |
} | |
}, | |
render: function(){ | |
var self = this; | |
var buttons = this.state.buttons.map(function(val){ | |
return <Button value={val} onMouseDown={self.onClickHandler} />; | |
}); | |
return ( | |
<div className="button-container">{buttons}</div> | |
) | |
} | |
}); | |
var ResultField = React.createClass({ | |
render: function(){ | |
return <input type="text" value={this.props.value} /> | |
} | |
}); | |
var Calculator = React.createClass({ | |
getInitialState: function(){ | |
return {value: "0"}; | |
}, | |
onKeyPress: function(val){ | |
this.setState({value: this.state.value + val.toString()}); | |
}, | |
onCalculate: function(){ | |
console.log('calculate') | |
this.setState({value: eval(this.state.value)}); | |
}, | |
render: function(){ | |
return ( | |
<div> | |
<p>Calculator</p> | |
<ResultField value={this.state.value} /> | |
<KeyBoard onKeyPress={this.onKeyPress} onCalculate={this.onCalculate} /> | |
</div> | |
) | |
} | |
}); | |
React.renderComponent(<Calculator />, document.body) | |
</script> | |
<!-- | |
JSBin: http://jsbin.com/seturifu/1/ | |
--> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://reactjs.co This is the official free online convention and tutorial book for React.JS Developers. React is not only the View (in MVC) anymore. ReactJS For Dummies: Why & How to Learn React Redux, the Right Way.