Search code examples
javascriptreactjsgithub-api

Sort user repositories by Stars Count in Github API


I'm building a reactjs app to show a specific user repositories. I need to sort them by star count but i dont know how to do it in React.

This is the api url which gives me stars number: https://api.github.com/users/cesar/repos

This is my actual code:

const UserRepositories = props => (
  <div className="user-repos">
    <ul>
      <li>
        <h2 className="repo-name">{props.repoName}</h2>
      </li>
      <li>
        <p className="repo-description">{props.repoDescription}</p>
      </li>
      <li>
        <span>
          <FontAwesomeIcon icon={Star} className="icon" />
          <span className="star-number">{props.starNumber}</span>
        </span>
      </li>
    </ul>
  </div>
);

And this is my map where i print the user repositories

    <div className="col-md-8">
      {githubRepo.map(name => (
        <UserRepositories
          key={name.id}
          repoName={name.name}
          repoDescription={name.description}
          starNumber={name.stargazers_count}
        />
      ))}
    </div>

Solution

  • You can sort your repositories using the sort function before calling the map function.

    <div className="col-md-8">
      {
        githubRepo.sort((a, b) => {
          if (a.stargazers_count > b.stargazers_count) return 1
          else if (a.stargazers_count < b.stargazers_count) return -1
          return 0
        }).map(name => (
          <UserRepositories
            key={name.id}
            repoName={name.name}
            repoDescription={name.description}
            starNumber={name.stargazers_count}
          />
        ))
      }
    </div>