grishma
grishma

Reputation: 81

How to navigate to a specific section of the page on page load using React Router?

I have added BrowserRouter to my React App

   <BrowserRouter>
     <Routes>
        <Route path="/" element={<App/>}/>
     </Routes>
   </BrowserRouter>

This is how my App looks like:

<div className="App">
  <NavBar/>
  <Home/>
  <Contact/>
</div>

and my component looks like this:

 <div id="contact" className="Contact"/>

When I try to navigate directly to contact section of my page by using the link "mySite.com/#contact" it does not navigate. Can you help me understand what is wrong?

Upvotes: 1

Views: 2119

Answers (2)

ihsany
ihsany

Reputation: 1050

For functional components useState hook works well with @grishma's answer.

useEffect(() => {
    const urlHash = window.location.hash;
    if (urlHash.length) {
        const element = document.getElementById(urlHash.substring(1));
        if (element) {
            element.scrollIntoView();
        }
    }
});

Upvotes: 0

grishma
grishma

Reputation: 81

I was able to solve my problem by using react lifecycle and scrollIntoView

  componentDidMount() {
    const urlHash = window.location.hash;
    if (urlHash.length) {
      const element = document.getElementById(urlHash.substring(1));
      if (element) {
        element.scrollIntoView();
      }
    }
  }

Upvotes: 5

Related Questions