2

In my react app I have a component that requires pagination. What I would like to do, is to actually allow for pagination to be done also from the url, not only the ui. So if I go to

localhost\users?page=2

I could share the link to anyone and they will be redirected to page 2 of the users component.

Currently I'm doing something like this

<Pagination
  page={state.pageNo}
  count={state.pageCount}
  variant="outlined"
  shape="rounded"
  color="secondary"
  showLastButton={state.pageCount > 7}
  showFirstButton={state.pageCount > 7}
  hideNextButton={state.pageCount === 1}
  hidePrevButton={state.pageCount === 1}
  onChange={onPageChange}

  renderItem={pageItem => (
    <PaginationItem
      type={'start-ellipsis'}
      component={Link}
      selected
      to={`${pageItem.page}`}
      {...pageItem}
    />
  )}
/>

And my route template looks something like this

 { path: 'users/:id', element: <UsersList /> }

So I can actually go to localhost/users/2 but this is not the right url form that I want to use, this is linked this to a UserDetails component and it should stay this way.

I'm able to extract the query params from the URL, but don't know how to use them

const query = useQuery();
const { page } = queryString.parse(query);

where useQuery is a helper function wrapping useLocation().search;

1 Answers1

2

You should use this.props.location.search or window.location.search and URLSearchParams in your Page Component

Usage:

const page = new URLSearchParams(this.props.location.search).get("page")

OR

const page = new URLSearchParams(window.location.search).get('page')

page variable you can pass to your Pagination component

// Example
componentDidUpdate() {
    const page = new URLSearchParams(this.props.location.search).get('page')
    // for example you are maintaining page inside state then
    this.setState({page})
}
Zia ur Rehman
  • 573
  • 3
  • 15
  • yes, I'm over that part I just don't know how to use exactly –  Mar 21 '21 at 09:36
  • check answer now – Zia ur Rehman Mar 21 '21 at 10:18
  • 1
    What I want is to when selecting page=3, the URL to become `localhost\users?page=3' . and 2nd when I copy thist url and paste it in another browser or window, the result should be that of the page=3. I'm not sure how what you've added is going to help me ? I'm already doing that I can extract the query and pars it but this is where I don't know how to continue. –  Mar 21 '21 at 13:28
  • onPageChange write this function in your question – Zia ur Rehman Mar 21 '21 at 13:49