0

Right now I have a table with some data from the github api. In the table you can click on the Stars heading and it sorts the list from 0 to *. My function works for one column. But how can I use this function over and over again for different columns?

My table headings :

<th>Name</th>
<th onClick={this.sortList}>Stars</th>

{* This should update value forks_count *}
<th onClick={this.sortList}>Forks</th>

My function:

What I do is I get my array and sort it based on stargazers_count. This works, however when I want to sort my Forks count.. stargazers_count should be forks_count. Is this possible?

sortList = () => {
    const items = this.props.repos;

    items.sort(function (a, b) {
        //stargazers_count should be forks_count when I click on forks heading
        return a.stargazers_count - b.stargazers_count;
    });

    this.setState({
        repos: items
    })

};

3 Answers 3

3

With closures:

<th>Name</th>
<th onClick={this.sortListBy("stargazers_count")}>Stars</th>

{* This should update value forks_count *}
<th onClick={this.sortListBy("forks_count")}>Forks</th>



sortListBy = (prop) => () => {
    const items = this.props.repos;

    items.sort(function (a, b) { 
        return a[prop] - b[prop];
    });

    this.setState({
        repos: items
    })

};
Sign up to request clarification or add additional context in comments.

1 Comment

All of them works but I like this one the most. It's short and simple, thank you!
3

Have an array of objects as configuration:

fields = [{ name: 'Stars', field: 'stargazers_count'}, { name: 'Forks', field: 'forks_count' }]

Now, have your th rendered inside a fields.map function something like this

fields.map(f => <th onClick={() => this.sortList(f.field)}> {f.name} </th>)

This will render all th according to your config array.

Now change your sortList function such that it takes field as a parameter.

sortList = (field) => {
...

items.sort(function (a, b) {
    return a[field] - b[field];
});

...

};

Comments

1

This should be possible using bind and taking the column name as argument like following :

<th>Name</th>
<th onClick={this.sortList.bind(this, 'stargazers_count')}>Stars</th>

{* This should update value forks_count *}
<th onClick={this.sortList.bind(this, 'forks_count')}>Forks</th>

sortList = (column) => {
    const items = this.props.repos;

    items.sort(function (a, b) {
        //stargazers_count should be forks_count when I click on forks heading
        return a[column] - b[column];
    });

    this.setState({
        repos: items
    })

};

3 Comments

@JustinTime On which parameter ?
On column in the function
@JustinTime Well you can see it is used right here : a[column]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.