Skip to content

Instantly share code, notes, and snippets.

@uberllama
Last active August 29, 2015 14:13
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save uberllama/487b6f94c615ae75e636 to your computer and use it in GitHub Desktop.
// WORKING VERSION
var Table = React.createClass({
getDefaultProps: function() {
return {
columns: [
{ propName: 'id', name: 'ID' },
{ propName: 'name', name: 'Name' }
]
};
},
getInitialState: function() {
return {
items: this.props.results || [],
sort: this.props.sort || { column: "id", order: "asc" }
};
},
handleSort: function(propName) {
// Removing this callback results in an invariant violation error
return function(event) {
if (this.state.sort.column === propName) {
newSortOrder = (this.state.sort.order === "asc") ? "desc" : "asc";
} else {
newSortOrder = 'asc';
}
this.setState({ sort: { column: propName, order: newSortOrder }});
}.bind(this);
},
render: function() {
var _this = this;
var headers = this.props.columns.map(function(column) {
return <th onClick={_this.handleSort(column.propName)}>{column.name}</th>;
});
var sortedItems = _.sortBy(this.state.items, this.state.sort.column);
if (this.state.sort.order === "desc") {
sortedItems.reverse();
}
var rows = sortedItems.map(function(item) {
return <Row key={item.id} {...item} />;
});
return (
<table>
<thead>
<tr>
{headers}
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
);
}
});
// BROKEN VERSION
var Table = React.createClass({
getDefaultProps: function() {
return {
columns: [
{ propName: 'id', name: 'ID' },
{ propName: 'name', name: 'Name' }
]
};
},
getInitialState: function() {
return {
items: this.props.results || [],
sort: this.props.sort || { column: "id", order: "asc" }
};
},
handleSort: function(propName) {
if (this.state.sort.column === propName) {
newSortOrder = (this.state.sort.order === "asc") ? "desc" : "asc";
} else {
newSortOrder = 'asc';
}
this.setState({ sort: { column: propName, order: newSortOrder }});
},
render: function() {
var _this = this;
var headers = this.props.columns.map(function(column) {
return <th onClick={_this.handleSort(column.propName)}>{column.name}</th>;
});
var sortedItems = _.sortBy(this.state.items, this.state.sort.column);
if (this.state.sort.order === "desc") {
sortedItems.reverse();
}
var rows = sortedItems.map(function(item) {
return <Row key={item.id} {...item} />;
});
return (
<table>
<thead>
<tr>
{headers}
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment