Using anchor tags in react-router 4

To scroll down to your anchor tags, you need to install React Router Hash Link, with:

npm install --save react-router-hash-link

then import Hash Link:

import { HashLink as Link } from 'react-router-hash-link';

and then use Hash Link, for example:

<Link to="/pathLink#yourAnchorTag">Your link text</Link>

and at the destination component, for example:

<div id= "yourAnchorTag">
      <p>Linked to here<p>
</div>

It is a known issue with react router. (https://github.com/ReactTraining/react-router/issues/394#issuecomment-220221604)

There is a solution as well. https://www.npmjs.com/package/react-router-hash-link this package solves the issue.

You have to use this Hash Link as the Link like below.

import { HashLink as Link } from 'react-router-hash-link';


If you have only few predictable anchor links, the simplest way to achieve the normal behavior is to manually scrollIntoView() of the element if you have the expected anchor tag in the Window.location.href.

class Page extends react.Component {
    componentDidMount() {
        if (this.$ref && location.href.includes('#my-ref')) {
            this.$ref.scrollIntoView({
                // optional params
                behavior: 'smooth',
                block: 'start',
                inline: 'center',
            });
        }
    }

     render() {
        return (
            // This is the div you want to scroll to
            <div ref={ref => {
                this.$ref = ref;
            }}>
                Other content
            </div>
        );
    }
}

Check Element.scrollIntoView() and React refs.


You can pass an object to Link, like this

<Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

ref. https://reacttraining.com/react-router/web/api/Link