I am trying to map few fields in array of objects, here in this case it is fieldnames and sort order.
I am trying to achieve server side sorting functionality where in the server takes the field name and sort type whenever I click on a field. I just need to map the field names with the sort type(ASCENDING or DESCENDING) .
I have written a sample where I am maintaining a sample array of objects with type. And on click of that column need I need to decide its sorting order
Can someone help here , Just need to achieve the tagging of sort order with the field name
Sandbox: https://codesandbox.io/s/hopeful-wescoff-08x8x
import React from "react";
import ReactDOM from "react-dom";
import { render } from "react-dom";
interface IState {
sorting: any;
}
interface IProps {}
export default class App extends React.Component<IProps, IState> {
constructor(props: any) {
super(props);
this.state = {
sorting: [{ firstName: "" }, { lastName: "" }]
};
}
sortHandler = name => {
const sorting = Object.keys(this.state.sorting).reduce((obj, key) => {
if (key === name) {
obj[key] = this.state.sorting[key] === "ASC" ? "DESC" : "ASC";
} else {
obj[key] = "";
}
return obj;
}, {});
this.setState({ sorting }, () => console.log(this.state.sorting));
};
render() {
return (
<div>
<span onclick={this.sortHandler("firstName")}> FirstName</span>
<span onclick={this.sortHandler("lastName")}> LastName</span>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);