I have an array:
people = [
{
name: "Kyle",
_id: "2"
},
{
name: Susan,
_id: "1"
}
]
I have a mapped list as such:
return (
<ul>
{people.map( (person) => {
return (
<li>
<span>{person.name}</span>
<span>{person.id}</span>
</li>
)
})}
</ul>
)
This is all working well, but how can I sort them, say based on "name"? I tried to use the [_.sortBy][1]
but couldn't figure out how it would fit to the context of React and map function. Using lodash, or underscore's _.sortBy would be appreciated.
Thanks!
In _.sortBy
you can pass the name of the field that will be used for sorting your collection, read more about _.sortBy
var Component = React.createClass({
getInitialState() {
return {
people: _.sortBy([
{ name: "Kyle", _id: 2},
{ name: "Susan", _id: 1}
], '_id')
}
},
sortBy(field) {
this.setState({
people: _.sortBy(this.state.people, field)
});
},
render: function() {
var peopleList = this.state.people.map( (person, index) => {
return (<li key={index}>
<span>{person.name}</span>
<span>{person.id}</span>
</li>);
})
return <div>
<a onClick={this.sortBy.bind(this, '_id')}>Sort By Id</a> |
<a onClick={this.sortBy.bind(this, 'name')}>Sort By Name</a>
<ul>{peopleList}</ul>
</div>;
}
});
Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With