grid react-redux
Starting point for creating JSFiddles with React. This uses React with Addons.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/5.0.5/react-redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/3.7.2/redux.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/clone/2.1.1/clone.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
CSS
.box{position: absolute}
JavaScript 1.7
var gridWidth = 15;
var gridHeight = 15;
var grid = [];
for(var y=0; y<gridHeight; y++) {
grid.push([]);
for(var x=0; x<gridWidth; x++) {
grid[y][x] = {c:0};
}
}
var reducer = function(state = grid, action) {
let newState = clone(state);
if(action.type==='CC') {
newState[action.payload.y][action.payload.x].c = action.payload.c;
}
return newState;
}
var store = Redux.createStore(reducer);
var colours = ['black', 'grey'];
var Provider = ReactRedux.Provider;
var connect = ReactRedux.connect;
var map = function(state) {
return {grid:state};
}
var Box = React.createClass({
shouldComponentUpdate(nextProps) {
return this.props.box.c !== nextProps.box.c;
},
width: 15,
handleClick: function(x, y) {
this.props.dispatch({type:'CC', payload: {c:1, x:x, y:y}});
},
render: function() {
console.log('boxrender')
var pos = {
top: this.props.y * this.width,
left: this.props.x * this.width,
width: this.width,
height: this.width,
background: this.props.colours[this.props.box.c]
}
return <div className="box" style={pos} onMouseOver={() => this.handleClick(this.props.x, this.props.y)}></div>
}
});
var ConnectedBox = connect(map)(Box);
var Grid = React.createClass({
render: function() {
console.log('grid render')
return (
<div>
{this.props.grid.map((row, y) => {
return row.map((box, x) => {
return <ConnectedBox key={'x'+x+'y'+y} box={box} x={x} y={y} colours={this.props.colours} />;
})
})}
</div>
)
}
});
var ConnectedGrid = connect(map)(Grid);
ReactDOM.render(
<Provider store={store}>
<ConnectedGrid colours={colours} />
</Provider>,
document.getElementById('container')
);