Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
reactjs grid
var Table = React.createClass({
getInitialState: function () {
var data = [];
for (var r = 0; r < this.props.rows; r++) {
data[r] = [];
for (var c = 0; c < this.props.columns; c++) {
data[r][c] = 0;
}
}
return {
data: data
};
},
onCellChange: function (row, column, value) {
this.state.data[row][column] = value;
this.setState({ data: this.state.data });
},
sum: function(data) {
return data.reduce(function(a, b) {
return a + b;
}, 0);
},
render: function () {
var rows = this.state.data.map(function(row, rowIndex) {
var cols = row.map(function(col, colIndex) {
var value = this.state.data[rowIndex][colIndex];
return (
<Cell
row={rowIndex}
column={colIndex}
value={value}
onChange={this.onCellChange}
/>
);
}.bind(this));
// add total cell to end of row
cols.push(<Total value={this.sum(row)} />);
return (
<Row>{cols}</Row>
);
}.bind(this));
var totalsRow = [];
var sum = 0;
for (var c = 0; c < this.props.columns; c++) {
var colVals = this.state.data.map(function(row) {
return row[c];
});
var colSum = this.sum(colVals);
sum += colSum;
totalsRow.push(
<Total value={colSum} />
);
};
totalsRow.push(<Total value={sum} />);
rows.push(totalsRow);
return (
<table>
{rows}
</table>
);
}
});
var Row = React.createClass({
render: function () {
return <tr className="cell-row">{this.props.children}</tr>;
}
});
var Total = React.createClass({
render: function () {
return <th className="total">{this.props.value}</th>;
}
});
var Cell = React.createClass({
onChange: function (e) {
this.props.onChange(
this.props.row,
this.props.column,
parseInt(e.target.value) || 0
);
},
render: function () {
return (
<td className="cell">
<input
type="number"
value={this.props.value}
onChange={this.onChange}
/>
</td>
);
}
});
React.render(
<Table columns={6} rows={6} />,
document.body
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.