1

React uses "#" in the URL so when I write

<a href="#specificAreaId">Click here to scroll to top</a>

it doesn't work as scrolling to the element which has id: specificAreaId. Instead, it navigates to another page. How can I do this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
WhiteDragon
  • 501
  • 1
  • 8
  • 14

4 Answers4

0

Create the anchor the way that is specified in Anchors.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
J.Doe
  • 17
  • 6
  • Peter Mortenson, I should have just told him to use the term "NAME" instead of "HREF" - that would have been best. Why didn't you just add that bit of detail? – J.Doe Jul 31 '21 at 00:18
0

You can use react-scrollable-anchor

Install it:

npm install --save react-scrollable-anchor

And import it in your component:

import ScrollableAnchor from 'react-scrollable-anchor'

Then use it like:

<a href='#myScrollSection'>Go to myScrollSection</a>
<ScrollableAnchor id={'myScrollSection'}>
     <div>Hello, World!</div>
</ScrollableAnchor>

You can read more here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
0

I am going with the assumption that you are using hash history in react-router. Try to use browser history instead.

Also it would be ideal if you create the anchor tags like:

<a href="pageUrl#specificAreaId">Click here to scroll to top</a>

You could also refer this post, regarding a similar issue:

Use anchors with react-router

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

You can try jQuery's 'animate scrollTop'.

$('html, body').animate({
  scrollTop: $('#specificAreaId').offset().top
}, 800);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ling yu
  • 66
  • 4