Last active
August 29, 2015 13:58
-
-
Save Tmw/10006617 to your computer and use it in GitHub Desktop.
Tiny codelock built with React.js
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> | |
<script src="//fb.me/react-0.9.0.js"></script> | |
<meta charset="utf-8"> | |
<title>Little code lock in React.js</title> | |
</head> | |
<body> | |
<script> | |
var Button = React.createClass({ | |
getInitialState: function(){ | |
return {count: 0}; | |
}, | |
handleMouseDown: function(){ | |
var newCount = (this.state.count < 9) ? this.state.count +1 : 0; | |
this.setState({count: newCount}); | |
if(this.props.valueChanged) this.props.valueChanged(this, newCount); | |
}, | |
render: function(){ | |
return React.DOM.button({onMouseDown: this.handleMouseDown}, this.state.count); | |
} | |
}); | |
var buttonContainer = React.createClass({ | |
getInitialState: function(){ | |
return {enteredCode:['0','0','0','0']}; | |
}, | |
valueChanged: function(obj, value){ | |
var buttonIndex = this.subItems.indexOf(obj); | |
var enteredCode = this.state.enteredCode; | |
enteredCode[buttonIndex] = value.toString(); | |
this.setState({enteredCode: enteredCode}); | |
this.checkCorrectness(); | |
}, | |
checkCorrectness: function(){ | |
if(this.state.enteredCode.join('') === this.props.codeToCrack){ | |
alert('Congratulations! You\'re in!'); | |
} | |
}, | |
componentWillMount: function(){ | |
this.subItems = [ | |
Button({valueChanged: this.valueChanged}), | |
Button({valueChanged: this.valueChanged}), | |
Button({valueChanged: this.valueChanged}), | |
Button({valueChanged: this.valueChanged}) | |
] | |
}, | |
render: function(){ | |
return React.DOM.div({className: 'list'}, this.subItems) | |
} | |
}); | |
// Initial render | |
React.renderComponent(buttonContainer({codeToCrack: "0123"}), document.body); | |
</script> | |
<!-- | |
JSBin: http://jsbin.com/lulivuya/3/edit | |
--> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment