skip to Main Content

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


  1. You can return to the top with a function:

      const handlePageChange = value => {
        window.scrollTo(0, 0);
        setPage(value);
      }
    

    And calling it in your button:

      ...
      <li key={value}>
        <button onClick={() => handlePageChange(value)}>{value}</button>
      </li>
    
    Login or Signup to reply.
  2. call the browser window object with below method scrollTo when you click on the Link

    window.scrollTo(0, 0);
    
    Login or Signup to reply.
  3. An 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

    import { useEffect } from 'react';
    import { useLocation } from 'react-router';
    
    const useScrollToTop = (ref: any) => {
      const location = useLocation();
    
      // ensure pages scroll to top
      useEffect(() => {
        if (ref?.current) {
          ref.current.scrollIntoView();
        }
      }, [ref?.current, location.pathname]);
    
      return null;
    };
    
    export default useScrollToTop;
    

    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):

    return (
      <div ref={ref}>
        <Header />
        <Navigation />
        <Content />
        <Footer ?>
      </div>
    );
    

    Now anytime the path changes, your end-user will scroll to the top of the page.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search