0

Is it possible with react router to maybe specify that Link should scroll to a component instead of rendering it? At the moment my components are rendered all at once (in a slightly long page). I have a nav bar and I would like when a user clicks on a Link in nav to scroll up/down to the appropriate component.

Manu
  • 1,632
  • 3
  • 17
  • 23
  • Do you really need `react-router` for this as this can simply be achieved by fragment identifier (`#`) on your anchor tag? – shriek Jan 19 '17 at 15:17
  • @shriek I've implemented **react-router** for practice and then I thought maybe there's an easy way of achieving this using it. – Manu Jan 19 '17 at 16:04

1 Answers1

0

I managed to solve my problem with a little help from this post here.

He's using es6, an es5 version of it will look like this:

const hashLinkScroll = function () {
  const {hash} = window.location;

  if (hash !== '') {
    const milliseconds = 0;

    setTimeout(function () { // eslint-disable-line prefer-arrow-callback
      const id = hash.replace('#', '');
      const element = document.getElementById(id);

      if (element) {
        element.scrollIntoView();
      }
    }, milliseconds);
  }
}

Watch out if you are using a function declaration rather than a function expression. The latter must be defined before it is called.

As for your router, you will have something like:

<Router history={browserHistory} onUpdate={hashLinkScroll}>your routes go here</Router>
Community
  • 1
  • 1
Manu
  • 1,632
  • 3
  • 17
  • 23