user3554072
user3554072

Reputation: 387

Search result pagination with React JS

How would one implement pagination for search using React?

Here's my code for returning users.

export default class SearchPanel extends Component {
  static propTypes = {
    isLoading: PropTypes.bool,
    users: PropTypes.array,
  }

  static contextTypes = {
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired,
  }

  static defaultProps = {
    isLoading: false,
    users: [],
  }

  constructor(props, context) {
    super(props, context);
  }

  render() {
    const searchResults = (this.props.isLoading)
      ? <h1>LOADING USERS</h1>
      : this.props.users.map((user) => <SearchResultUser key={user.username}     {...user} />);

    return (
      <div className="ibox-content">
          {this.props.users}
      </div>
    )
  }
}

Note: I've kept most of the html out of the render to keep the code looking simple for this question.

So in a nutshell, this.props.users returns an array of users, I just need to be able to paginate the result by lets say 5 per page.

Upvotes: 0

Views: 2821

Answers (1)

Samuli Hakoniemi
Samuli Hakoniemi

Reputation: 19049

Use this function:

getUsers(page, amount) {
  return this.props.users.filter(function(item, i) {
    return i >= amount*(page-1) && i < page*amount
  });
}

E.g {() => getUsers(1, 5)} will return users between 1-5, where {() => getUsers(2,5)} will return users between 6-10.

Example: http://codepen.io/zvona/pen/GpEdqN?editors=001

Upvotes: 2

Related Questions