skip to Main Content

I’m working on a Next.js application that has pagination.

My pagination links are at the bottom of the page. When I scroll to the bottom and click a new page, I stay at the bottom of the page. What I want is to start back up at the top of the page.

The Google AI says to do this:

import { useEffect } from 'react';
function YourComponent(){
    useEffect(()=>{
        window.scrollTo(0,0);
    }, []);
}

But that doesn’t work. I have tried other variations of using window.scrollTo(x,y) and element.scrollIntoView() but nothing I do works.

How do I fix this?

I am using:

  • next v13.2.3 – with "traditional" pages routing
  • react v18.2.0

2

Answers


  1. Chosen as BEST ANSWER

    After more research, I have found a solution. My Google search criteria was this:

    https://www.google.com/search?q=%40elastic%2Freact-search-ui+paging+starts+at+bottom+instead+of+top

    Which brought up this result:

    https://github.com/elastic/search-ui/issues/500

    With this solution:

    onSearch: async (state: RequestState,
        queryConfig: QueryConfig,
        next: (
            state: RequestState,
            queryConfig: QueryConfig
        ) => Promise<ResponseState>
    ) => {
        const response = await next(state, queryConfig);
        window.scrollTo({
            top: 0,
            behavior: "smooth",
        });
        return response;
    },
    

    Which worked beautifully!


  2. Use next.js Link component it will automaticly scroll back at the start of page.

    import Link from 'next/link';
    <Link href={`?page=1`}>1</Link>
    

    on the other hand if you want to do it using js

    window.scrollTo({ top: 0, behavior: 'smooth' });
    

    if you want to make that scroll smoother using css style html tag like.

    html {
       scroll-behavior: smooth;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search