Reputation: 2481
I have an app that user can CRUD thread and main structure looks like this,
export default function Dashboard(){
return(
<Fragment>
<CreateBoard />
<BoardList />
</Fragment>
)
}
Dashboard
will be called in App.js
.
BoardList
import { getBoards, deleteBoard } from "../../actions/boards"
export class BoardList extends Component {
static propTypes = {
boards: PropTypes.array.isRequired,
getBoards: PropTypes.func.isRequired,
deleteBoard: PropTypes.func.isRequired,
}
componentDidMount() {
this.props.getBoards();
}
render(){
return (
<Fragment>
<h2>Boards</h2>
<table className="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Author</th>
<th>Title</th>
<th>Created</th>
<th>Updated</th>
<th />
</tr>
</thead>
<tbody>
// this sort does not work
{this.props.boards.length > 0 && this.props.boards.sort((boardA, boardB) => boardA.id < boardB.id)
.map(board => (
<tr key={board.id}>
<td>{board.id}</td>
<td>{board.author}</td>
<td>{board.title}</td>
<td>{board.created}</td>
<td>{board.updated}</td>
<td>
<button
className="btn btn-danger btn-sm"
onClick={this.props.deleteBoard.bind(this, board.id)}
>
Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</Fragment>
)
}
}
const mapStateToProps = state => ({
boards: state.boards.boards
})
export default connect(mapStateToProps, {getBoards, deleteBoard})(BoardList)
Even though I sort it, it always sort my list descendant order(the newer post goes top). How can I fix it without rendering it every time?
Upvotes: 0
Views: 75
Reputation: 4214
It might be cleaner to sort
in the return function instead of the JSX. Also you need to clone the props into a new array that can be sorted.
render() {
const sortedBoard = [...this.props.boards].sort((boardA, boardB) => {
return boardA.id > boardB.id;
});
const sortedRows = sortedBoard.map(board => {
return (
<tr key={board.id}>
<td>{board.id}</td>
<td>{board.author}</td>
<td>{board.title}</td>
<td>{board.created}</td>
<td>{board.updated}</td>
<td>
<button
className="btn btn-danger btn-sm"
onClick={this.props.deleteBoard.bind(this, board.id)}
>
Delete
</button>
</td>
</tr>
);
});
return (
<Fragment>
<h2>Boards</h2>
<table className="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Author</th>
<th>Title</th>
<th>Created</th>
<th>Updated</th>
<th />
</tr>
</thead>
<tbody>{this.props.boards.length && { sortedRows }}</tbody>
</table>
</Fragment>
);
}
Note sort
can be kind of tricky...
let a = [ '1', '2', '10', '3' ];
a.sort();
// [ '1', '10', '2', '3' ]
let b = [1, 2, 10, 3];
b.sort((x,y) => { return x-y });
// [ 1, 2, 3, 10 ]
Upvotes: 3