Skip to content

Instantly share code, notes, and snippets.

@Tmw
Last active August 29, 2016 17:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tmw/10008243 to your computer and use it in GitHub Desktop.
Save Tmw/10008243 to your computer and use it in GitHub Desktop.
Poorly written calculator in React.js + JSX
<!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>
@przeor
Copy link

przeor commented Aug 29, 2016

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment