Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.