I have a react app, I use react-router v.4 and I use pagination from Jason. http://jasonwatmore.com/post/2017/03/14/react-pagination-example-with-logic-like-google
Everything is working fine but, when I change the route and then change the route back, the pagination changes the current page back to page 1.
How can I keep the page state when route change?
To detect route change with React Router, we can use the useLocation hook. import { useEffect } from "react"; import { useLocation } from "react-router-dom"; const SomeComponent = () => { const location = useLocation(); useEffect(() => { console. log("Location changed"); }, [location]); //... };
Firstly wrap all the content of your page inside the return function inside the . Next, create the induvial routes inside the component. For each route, we have the path and the element props, these tell the path on the address bar and the component to be rendered out respectively.
react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.
Let’s have a look at how to make pagination in ReactJS. How to Implement Pagination Using React Hooks and React Paginate? npx create-react-app react-pagination cd react-pagination Based on your package manager, install Axios and React Paginate. Now, open App.js and make the necessary changes.
These electronics pages are rendered on a web browser and are called web pages. Also, these pages and the content in these pages, which is supposed to be rendered are related to each other using React.js pagination.
The default value for the current page is 1, items per page are 10, and the page range to be displayed is 5. There are a lot of other packages available which you can use as per your requirements. For example, end page = 11+ 4 = 15 React.js pagination library can be used directly for paging functionality for any list of items.
Create your react app npx create-react-app paginateapp and install axios npm i axios --save and also react-paginate npm i react-paginate --save. Now go to your src directory and open your app.js file.
With react router, there are multiple ways to handle this: The props from the Router pass down to you component, you can use a param:
<Route path="/items/:page" component={Component} />
and /items/1, /items/2 and use
props.match.params.page
Based on a quick view at the example, here:
this.setPage(this.props.match.params.page || this.props.initialPage)
And to change the url, in the onChangePage or even in the onClick handler, use something like
this.props.history.push(`/items/${page}`
.
You could also use the location.pathname prop and parse the string, or use item?page=1
and parse location.search, etc.
If you want to maintain state globally and not from the router, you could use Redux.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With