How to sort the data in asc and desc order in table
Use localeCompare()
to sort in alphabetical order.
Have the sorting done in reducer while the component just dispatches the "sort" action. Every re-sort will cause a component re-render for jobList
prop
(in mapStateToProps
) is updated.
In reducer:
const initialState = {
jobList: [],
};
export const jobList = (state = initialState, action) => {
switch(action.type) {
case Action.SORT_ALPHA_ASC:
const { sortKey } = action.payload;
const jobList = [ ...state.jobList ]
.sort((a, b) => a[sortKey].localeCompare(b[sortKey]));
return { ...state, jobList };
default:
return state;
}
}
In your component:
// alphaSort will dispatch action: SORT_ALPHA_ASC
const { jobList, alphaSort } = this.props;
if (! jobList || jobList.length < 1) {
// no job list
return null;
}
return (
<table>
<thead>
{ /* TODO: use th/td */ }
<SomeIcon name='asc-technology' onClick={() => alphaSort('technology')} />
<SomeIcon name='asc-jdname' onClick={() => alphaSort('jdName')} />
{ /* TODO: other fields */ }
</thead>
<tbody>
{
jobList.map((job) => ({
<tr key={job.id}>
<td name="technology">{job.technology}</td>
<td title={job.jdName}>
<div className="jdName">{job.jdName}</div>
</td>
{ /* TODO: other fields */ }
</tr>
}))
}
</tbody>
</table>
);
NOTE: descending alpha sort and other fields will be for the OP to continue. :)