I have a pagination component (React). I need the scroll to be moved to the top when changing pages. Can someone help me?
const MAX_BTN = 9;
const MAX_BTN_LEFT = (MAX_BTN - 1) / 2;
const Pagination = ({items, limit = 20, page, setPage}) => {
const pages = items !== null && Math.ceil(items.total_results / limit);
const startBtn = Math.max(page - MAX_BTN_LEFT, 1);
return (
<ul className="pagination">
{Array(Math.min(MAX_BTN, pages)).fill()
.map((_, i) => i + startBtn)
.map(value => (
<li key={value}>
<button onClick={() => setPage(value)}>{value}</button>
</li>
))
}
</ul>
)
}
export default Pagination;
3
Answers
You can return to the top with a function:
And calling it in your button:
call the browser
window
object with below methodscrollTo
when you click on the LinkAn elegant way to handle this is by creating a single
ref
for the top-most part of your app. Then pass the ref into a hook which handles scrolling to the top of the page when the pathname changes.Here’s a simple hook I use (type definitions can be cleaned up):
useScrollToTop.ts
Now at the top of your app’s very first element add the reference.
App.js: (or whatever component)
import useScrollToTop from './useScrollToTop';
Then create a new empty ref:
const ref = useRef<HTMLDivElement | null>(null);
Pass the ref into the hook:
useScrollToTop(ref)
Define the ref on the top-most part of your app (example inner components):
Now anytime the path changes, your end-user will scroll to the top of the page.