3

I want to make a React website and want it to use inpage links. I know that in normal html you can just use:

<a href='#someheader'>link</a>

<h1 id='someheader'>This is an example</h1>

In react though, I am using multiple separate files for each part of the website. So for the navigation bar I have a file and for the body I have a file etc. I have tried the above technique, but it doesn't seem to work.

Is it because of the link and the place I want the link to go to are in different pages, or is it because of something else?

Daniel F.
  • 95
  • 8
  • If you already use react-router, check https://medium.com/javascript-in-plain-english/creating-a-hash-anchor-link-effect-with-react-router-a63dcb1a9b0e – Muhammed B. Aydemir Sep 02 '20 at 14:44
  • If you are using `react-router`, the best possible solution I had was to assign a `ref` to the section I want to scroll to when clicking on the `Nav` and then doing `scrollIntoView`. – Zameer Haque Sep 02 '20 at 15:10

2 Answers2

1

For this route:

<Route path="/about" component={AboutPage} />

## Link to anchor on same page

<!-- AboutPage.js -->
<a href='#someheader'>Jump to someheader</a>

Go to anchor someheader on the current page (Not related to React-Router - this is simple HTML behavior). a element docs

## Link to anchor on another page (Tricky)

Jump to someheader point on about page.

This code will work (But you do not get the "power/features" of React-Router):

<!-- HomePage.js -->
<!-- Simple href to anchor -->
<a href='about#someheader'>
  Go to about page and jump to someheader
</a>

But when using the <Link> component to navigate - the scroll to #hash will not work/scroll. Related github issue: https://github.com/ReactTraining/react-router/issues/394

<!-- HomePage.js -->
<!-- anchor not working -->
<Link to='about#someheader'>
  Go to About page without jumping to #someheader section
</Link >

How to solve this (True to Sep 20)?

  1. Use this package: https://www.npmjs.com/package/react-router-hash-link
  2. More ideas (Related/duplicate stackoverflow Q): Using anchor tags in react-router 4 // How to use normal anchor links with react-router
Ezra Siton
  • 6,887
  • 2
  • 25
  • 37
0

Check out react-router which should solve your problem.

https://reactrouter.com/web/guides/quick-start

N. Ahlers
  • 344
  • 3
  • 8
  • 1
    Not exactly true. You can add `hash` to the URL by react-router (But the scroll into view will not work without some custom code). Read this issue: https://github.com/ReactTraining/react-router/issues/394 – Ezra Siton Sep 02 '20 at 15:42
  • 1
    Yeah you're correct. Missread the question. Thank you for mentioning that. Im trying to get my reputation up lol – N. Ahlers Sep 03 '20 at 07:28