最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Scroll to top when using pagination in React - Stack Overflow

programmeradmin4浏览0评论

I am loading data card and when I press pagination buttons, the data changes but screen remains in the same place. How do I scroll to top when button is pressed? The application is a SPA so maybe that is causing the issue?

const getCoinsData = async () => {
    try {
      const response = await Axios.get(
        `;per_page=100&page=${activePage}&sparkline=true&price_change_percentage=1h%2C24h%2C7d`
      );
      setData(response.data);
      setLoading(false);
    } catch (e) {
      console.log(e);
    }
  };

I am loading data card and when I press pagination buttons, the data changes but screen remains in the same place. How do I scroll to top when button is pressed? The application is a SPA so maybe that is causing the issue?

const getCoinsData = async () => {
    try {
      const response = await Axios.get(
        `https://api.coingecko./api/v3/coins/markets?vs_currency=usd&per_page=100&page=${activePage}&sparkline=true&price_change_percentage=1h%2C24h%2C7d`
      );
      setData(response.data);
      setLoading(false);
    } catch (e) {
      console.log(e);
    }
  };
Share Improve this question edited Jan 17, 2022 at 0:24 Husnain Mehmood asked Jan 16, 2022 at 21:45 Husnain MehmoodHusnain Mehmood 1194 silver badges15 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Another way you could do it is with a useEffect in the ponent gets the new data on page change

edit should have updated the dependencies. I am assuming your list is ing in as a variable named data. Just add that to the dependency array. You could use your data object or your isSuccess boolean if you have one.

    useEffect(()=>{
        window.scrollTo({top: 0});
    },[data])

Since the application is a SPA, the page is likely not reloading when you move to next page. You'll have to manually scroll to the top of the ponent.

To do that, add a ref to the wrapper of the content that you want to scroll to the top of:

const wrapperRef = useRef(null);

// ... blablabla ponent stuff

return {
  <div ref={wrapperRef}></div>
}

Then just make sure you next page button handler has access to the ref:

const handleNextPageButtonClick = async () => {
  await getNextPage();
  wrapperRef.current.scrollIntoView();
}

Using window.scrollTo({top: 0}) (as suggested by epicmau5time) worked for me, however, I'd suggest using useMemo rather than useEffect. I'm working on a SPA as well, and using Pagination. So I used useMemo and included the currentPage variable as its dependency.

useMemo(() => {
    window.scrollTo({top: 0})
  }, [currentPage])
发布评论

评论列表(0)

  1. 暂无评论