Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort mapped list with Lodash on ReactJS

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!

like image 583
Emo Avatar asked Dec 14 '22 10:12

Emo


1 Answers

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

like image 143
Oleksandr T. Avatar answered Dec 17 '22 00:12

Oleksandr T.