Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
React scroll page to the top after transition

I want my application to go to the top of the page when another page within the site is clicked. I have used the code from: https://v5.reactrouter.com/web/guides/scroll-restoration and put in a separate file.

import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

What I have tried:

I have placed <ScrollToTop /> before <Switch /> and after <BrowserRouter />as in the docs (these are in separate files).

Unlike the docs, the <App /> in my application is in a separate file, so <ScrollToTop /> is not placed near it.

When I console.log, I see it being hit at the correct instance (when there is a page change), but nothing occurs. I have also looked into many stackoverflow posts concerning the same issue, but I could not incorporate their suggestions.

What are possible issues:

Calling window.scrollTo(0, 0) outside the function does not seem to work. Are there any alternatives to this function?

Is the placement of <ScrollToTop /> incorrect? Does it have to be called near the <App />?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Welcome to Stackoverflow @user19251203

You have already gone half the way. You really don't need to create a component for it. You can create a custom hook and place it in your <App /> and then call it:

function App() {

  // Scroll to top on every transition custom hook
  const useScrollToTop = () => {
    const { pathname } = useLocation();

    useEffect(() => {
      window.scrollTo(0, 0);
    }, [pathname]);
  };

  useScrollToTop();

  return (
    <div className="App">
      .......
    </div>
  )
}

This way whenever you go to a new page, it scrolls to the top of the page.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!