score:1

Accepted answer

i won't edit your code, but outline a principle of how to achieve your solution.

you need to keep your pagination state in your component. then, you need to do 2 things:

  • when you change the page, set your query parameter in the url to this page number. also keep that page number in your state, as your pagination is a controlled component now.
  • when you initially load the component, get a page number from the url params and set your pagination state with this information. so table can be displayed on that page.

here is the simplest working example:

import react from 'react';
import './app.css';
import { usehistory } from "react-router-dom";

const app = (props: object) => {
const history = usehistory();

let search = window.location.search;
let params = new urlsearchparams(search);

const [page, setpage] = react.usestate<number>( parseint("" + params.get('page')))

const paginate = (n: number) => {
    setpage(n)
    history.push({
        pathname: '/',
        search: '?page=' + n
      })
}

return (
<div >
    <div onclick={()=>paginate(1)} style={page===1 ? {fontsize:30} : {}}>1</div>
    <div onclick={()=>paginate(2)} style={page===2 ? {fontsize:30} : {}}>2</div>
</div>
);
}

export default app;

codesandbox:

https://codesandbox.io/s/react-pagination-7do5s

alternatively, search, params and page variables could be calculated and set only after the first mount, in react.useeffect hook. up to you.

please note this is a typescript file, if you're only using javascript, remove type. also i am using react-router-dom to change query parameter in the url. this will only work, when this component is wrapped by router.

my index.tsx file:

reactdom.render(
  <react.strictmode>
      <router>
        <app />
    </router>
  </react.strictmode>,
  document.getelementbyid('root')
);

score:0

for people who are looking at this solution, after the react-router upgrade we use navigate("/page") after importing usenavigate instead of history.push()


Related Query

More Query from same tag