I Am trying to sort a table with the list which is retrieving through API. I am doing this in react + typescript. I am facing the type error. Kindly, help me. Below is my code. So by hovering on Name , Type , Color this should sort but sorting is not working. kindly go through the code and help me do sorting .
export interface VehicleListProps {
vehicle: VehicleState;
listVehicles: (limit: number, skip: number) => void;
addVehicle: (id: string) => void;
deleteVehicle: (id: string, limit: number, skip: number) => void;
}
const Row = ({name, type , color }) => (
<div className="row">
<div>{name}</div>
<div>{type}</div>
<div>{color}</div>
</div>
);
const VehicleList: React.FC<VehicleListProps> = (props) => {
constructor(props); {
this.state = {
data: vehicle
};
this.compareBy = compareBy.bind(this);
this.sortBy = sortBy.bind(this);
}
function compareBy(key) {
return function (a, b) {
if (a[key] < b[key]) return -1;
if (a[key] > b[key]) return 1;
return 0;
};
}
function sortBy(key) {
let vehicle = [...this.state.data];
vehicle.sort(this.compareBy(key));
this.setState({data: vehicle});
}
const rows = this.state.data.map( (rowData) => <Row {...rowData} />);
return (
<div>
<div className="row gap-20 masonry pos-r">
<Table id="dataTable" className="table table-hover table-striped">
<thead className="thead-dark" >
<tr>
<th onClick={() => this.sortBy('name')}>Name</th>
<th onClick={() => this.sortBy('type')}>Type</th>
<th onClick={() => this.sortBy('color')}>Color</th>
<th></th>
</tr>
</thead>
<tbody>{
vehicle.page.collection.map((vehicle, idx) => {
return (
<tr key={idx}>
<td><a className="vehicleName" href={`/vehicles/${vehicle.id}`}>{vehicle.name}</a></td>
<td>{vehicle.type}</td>
<td>{vehicle.color}</td>
</tr>
)
})
}</tbody>
</Table>
</div>
</div>
</div>
);
}