3

I am using react-boilerplate (3.4.0) with react-router internally for the routing.

I have tried to create a Link with : < a href="#anchor-tag" >< /a >

When I click on it I expect to scroll to the div with id=anchor-tag

It just scroll to the top of the page, even if I use a Link component instead of a < A > tag. Does we have to care about use < A > or < Link > ?

How should we create anchor tag in react-router ?

Adrien Gadaud
  • 149
  • 2
  • 12

3 Answers3

3

This might be a while late but what you can do is add this to your component:

import ReactDOM from 'react-dom';

... some more codez...

componentDidUpdate() {
  const anchor = this.props.location.hash.replace('#', '');

  if (anchor) {
    const domElement = ReactDOM.findDOMNode(this.refs[hash]);
    if (domElement) {
      domElement.scrollIntoView();
    }
  }
}

and then on your actual element that you want to navigate to, you need to add the ref attribute, like this:

<h1 ref="my-anchor">Hello World</h1>

The link element is going to look just like a regular link:

<a href="/about#my-anchor>Go To Anchor</a>

Or with react-router:

<Link key="my-anchor" to="/about#my-anchor">Go To Anchor</Link>

This works with react-router 2.6.1 - not sure about later versions at this point.

Hope this helps!

alengel
  • 4,368
  • 3
  • 21
  • 28
1

Improved answer above:

componentDidMount() {
  const anchor = this.props.location.hash;

  if (anchor) {
    const domElement = document.querySelector(anchor);
    if (domElement) {
      domElement.scrollIntoView();
    }
  }
}
Vladimir Tolstikov
  • 2,463
  • 21
  • 14
0

I highly recommend to use the package from Rafael Pedicini called react-router-hash-link.

Live example right there. It's working well and the code is clean.

Laura
  • 8,100
  • 4
  • 40
  • 50