Adrien Gadaud
Adrien Gadaud

Reputation: 149

How to create Anchor Tag in react-router?

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 ?

Upvotes: 3

Views: 8228

Answers (3)

Laura
Laura

Reputation: 8640

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.

Upvotes: 0

Vladimir Tolstikov
Vladimir Tolstikov

Reputation: 2683

Improved answer above:

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

  if (anchor) {
    const domElement = document.querySelector(anchor);
    if (domElement) {
      domElement.scrollIntoView();
    }
  }
}

Upvotes: 1

alengel
alengel

Reputation: 4958

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!

Upvotes: 3

Related Questions