Skip to content

Instantly share code, notes, and snippets.

@aadsm
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save aadsm/8fff7196366b885bb182 to your computer and use it in GitHub Desktop.

Select an option

Save aadsm/8fff7196366b885bb182 to your computer and use it in GitHub Desktop.
ReactJS animated-boxes
p {
font: 12px/16px Arial;
margin: 10px 10px 15px;
}
button {
font: bold 14px/14px Arial;
margin-left: 10px;
}
#grid {
margin: 10px;
}
.box-view {
width: 20px; height: 20px;
float: left;
position: relative;
margin: 8px;
}
.box {
border-radius: 100px;
width: 20px; height: 10px;
padding: 5px 0;
color: #fff;
font: 10px/10px Arial;
text-align: center;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
<title>Animated Boxes with ReactJS</title>
<link rel="stylesheet" href="index.css" />
<script src="http://fb.me/react-0.8.0.js"></script>
<script src="http://fb.me/JSXTransformer-0.8.0.js"></script>
</head>
<body>
<script type="text/jsx" src="index.js"></script>
</body>
</html>
function BoxController() {
this.count = 0;
this.top = 0;
this.left = 0;
this.color = 0;
this.content = 0;
}
BoxController.prototype.tick = function() {
var count = this.count += 1;
this.top = Math.sin(count / 10) * 10;
this.left = Math.cos(count / 10) * 10;
this.color = count % 255;
this.content = count % 100;
}
/**
* Box Component
*/
var Box = React.createClass({
render: function() {
var data = this.props.data;
var divStyle = {
top: data.top,
left: data.left,
backgroundColor: "rgb(0,0," + data.color + ")"
};
return (
<div className="box-view">
<div className="box" style={divStyle}>{data.content}</div>
</div>
);
}
});
/**
* Main Component
*/
var Main = React.createClass({
getInitialState: function() {
var N = 300;
var boxes = [];
for (var i = 0; i < N; i++) {
boxes[i] = new BoxController();
}
return {boxes: boxes};
},
tick: function() {
var boxes = this.state.boxes;
boxes.forEach(function(box) {
box.tick();
});
this.setState({boxes: boxes});
this.animationFrame = window.requestAnimationFrame(this.tick);
},
componentDidMount: function() {
this.animationFrame = window.requestAnimationFrame(this.tick);
},
componentWillUnmount: function() {
window.cancelAnimationFrame(this.animationFrame);
},
render: function() {
var boxNodes = this.state.boxes.map(function (box, index) {
return <Box key={index} data={box}></Box>;
});
return <div id="grid">{boxNodes}</div>;
}
});
React.renderComponent(<Main></Main>, document.querySelector("body"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment