Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to anchor (section of page) in react-router-v6

I'm trying to use the tags to scroll to a part of the page. For example:

<Link to="/#first">Go</Link>
...
<div id="first">The first section</div>

This does not seem to work with react router v6. The solutions I have found are all for previous versions of react router.

I have found that I can use reloadDocument to force the reload and that will work, but I want to implement a smooth scroll down to the element if coming from the same page. I would use refs, but I need to be able to link to these sections from other pages as well.

like image 538
user12457151 Avatar asked Oct 24 '25 04:10

user12457151


1 Answers

You can scroll using JS

So instead of

<Link to="/#first">Go</Link>
...
<div id="first">The first section</div>

you would have

<button 
  onClick={() => document.getElementById('first')?.scrollIntoView()}
>
  Go
</button>
...
<div id="first">The first section</div>
like image 188
Al Vedder Avatar answered Oct 26 '25 18:10

Al Vedder