react randomly moving text areas
by phsiao2000
HTML
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
CSS
.time {
font-family: monospace;
}
JavaScript 1.7
/**
* @jsx React.DOM
*/
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
var RandomTest = React.createClass({
onChange: function(ev) {
this.props.onNewWord({key:this.props.key, value:ev.target.value});
},
render: function() {
return <textarea onChange={this.onChange} style={{backgroundColor: this.props.key == 0? '#ff0000' : '#00ff00'}} defaultValue={this.props.value}></textarea>;
}
});
var Test = React.createClass({
getInitialState: function() {
var s = (this.props.yourWords || "and did those feet in ancient time").split(" ");
var e={};
var r = s.map(function(v,i){e[i] = v; return i;});
return {
time: new Date(),
randoms: r,
orig: e,
interval: 1000
};
},
handleNewWord: function(ev){
var newWords = this.state.orig;
newWords[ev.key] = ev.value;
this.setState({orig: newWords});
this.setState({interval: ev.value.length * 300});
},
componentDidMount: function() {
var randomize = function (){
var newList = shuffle(this.state.randoms);
this.setState({time: new Date(), randoms: newList});
again();
}.bind(this);
var timer;
var again = function() {
console.log("again");
timer = setTimeout(randomize, this.state.interval);
}.bind(this);
again();
},
render: function() {
var newWords = this.state.randoms.map(function(v,i){
return this.state.orig[i];
},this).join(" ");
var moveTextAreas = this.state.randoms.map(function(v) {
return <RandomTest key={v} onNewWord={this.handleNewWord} value={this.state.orig[v]} />;
},this);
return (
<div class='time'>
{'' +...