How to update url hash when scrolling through sections in ReactJS

Viewed 1834

I've been struggling with that issue for 2 hours or so and can't find a way to do it.

I would like to update my url hash (#home, #about etc..) when i'm scrolling through those sections and by the same way highlight the current section in my navbar. I've found different answers in Jquery but the thing is that i'm using ReactJS and i've been told that it is not a good idea / useful to use Jquery with ReactJS.

I've also found and tried this package : https://www.npmjs.com/package/react-scrollable-anchor But the problem is the hash update only when the scrolling is over.

Edit :

<ul>
  <li>
      <a href="#">Home</Link>
  </li>
  <li>
      <a href="#about">About</Link>
  </li>
  <li>
      <a href="#skills">Skills</Link>
  </li>
</ul>

When i'm clicking on About my url then goes as : localhost:3000/#about and automatically scroll to this section, everything is fine from here. But if I scroll(without clicking anywhere) to the Skills section then i want the url to automatically go to localhost:3000/#skills and the navbar hightlight the Skills.

Hope you can help me through this issue. Thanks !

1 Answers

You should simply use 'react-router-dom' library for routing and handling Url paths. they has very clear documentation https://reactrouter.com/web/example/basic. For You help Simply define the path in the to prop of Link where you want to go !

       <ul>
          <li>
            <Link to="/test">Home</Link>
          </li>      
          <li>
            <Link to="/dashboard">Dashboard</Link>
          </li>
        </ul>

Now simply navigate to that declared path by wrapping it in the

          <Route exact path="/test">
            <Home />
          </Route>

By doing all this.Url Hash will not been a problem any more ;)

Related