Here is a working code on how to implement a table that can be filtered and sorted. Here the sorting happens whenever you click on the title bar. this.props.datafor this example:
[
{"Type":"foo", "Name": 0, "Modified": "3/20/2017", "ModifiedBy":"Me"},
{"Type":"foo", "Name": 2, "Modified": "3/15/2017", "ModifiedBy":"You"},
{"Type":"buzz", "Name": 1, "Modified": "3/20/2017", "ModifiedBy":"Me"}
];
And the reaction class:
const SortableFilterableTable = React.createClass({
getInitialState: function(){
return({data:this.getSortedData('Type')});
},
render: function(){
let rows = this.state.data.map((rowData) =>{
return(
<tr>
<td>{rowData.Type}</td>
<td>{rowData.Name}</td>
<td>{rowData.Modified}</td>
<td>{rowData.ModifiedBy}</td>
</tr>
);
});
return(
<div>
<input type="text" id="filter" onChange={this.filterTable}/>
<table>
<thead>
<tr>
<th onClick={()=>this.setSortedData('Type')}>Type</th>
<th onClick={()=>this.setSortedData('Name')}>Name</th>
<th onClick={()=>this.setSortedData('Modified')}>Modified</th>
<th onClick={()=>this.setSortedData('Modified By')}>Modified By</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
);
},
setSortedData: function(sortBy){
this.setState({data:this.getSortedData(sortBy)});
},
getSortedData: function(sortBy){
let dataToSort = this.props.data;
dataToSort.sort(function(a,b){
if(sortBy === 'Type')
return a.Type - b.Type;
if(sortBy === 'Name')
return a.Name - b.Name;
if(sortBy === 'Modified')
return a.Modified - b.Modified;
if(sortBy === 'Modified By')
return a.ModifiedBy - b.ModifiedBy;
});
return dataToSort;
},
filterTable: function(e){
let text = e.target.value;
let filterFunc = (value) => {
console.log(value)
if(value.Type.indexOf(text) >= 0 || value.Name.toString().indexOf(text) >= 0 || value.Modified.indexOf(text) >= 0 || value.ModifiedBy.indexOf(text) >= 0)
return true;
console.log('made it ')
return false;
};
let dataForState = this.props.data.filter(filterFunc);
this.setState({data:dataForState});
}
});
. , , Name.