React table component example
by Chetan Hanumantha
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/JSXTransformer.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0/react-with-addons.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/black-tie/jquery-ui.css">
<script src="http://facebook.github.io/react/js/jsfiddle-integration.js"></script>
<div id="example"></div>
CSS
.datatable tr {
background-color: #ffffff;
color: #000;
}
JavaScript 1.7
var cols = [
{ key: 'firstName', label: 'First Name' },
{ key: 'lastName', label: 'Last Name' }
];
var data = [
{ id: 1, firstName: 'John', lastName: 'Doe' },
{ id: 2, firstName: 'Clark', lastName: 'Kent' }
];
var Table = React.createClass({
render: function() {
var headerComponents = this.generateHeaders(),
rowComponents = this.generateRows();
return (
<table class="datatable">
<thead> {headerComponents} </thead>
<tbody> {rowComponents} </tbody>
</table>
);
},
generateHeaders: function() {
var cols = this.props.cols; // [{key, label}]
// generate our header (th) cell components
return cols.map(function(colData) {
return <th key={colData.key}> {colData.label} </th>;
});
},
generateRows: function() {
var cols = this.props.cols, // [{key, label}]
data = this.props.data;
return data.map(function(item) {
// handle the column data within each row
var cells = cols.map(function(colData) {
// colData.key might be "firstName"
return <td> {item[colData.key]} </td>;
});
return <tr key={item.id}> {cells} </tr>;
});
}
});
React.render(<Table cols={cols} data={data}/>, document.getElementById('example'));