I
I
Igor Shumilovsky2015-10-29 11:36:59
React
Igor Shumilovsky, 2015-10-29 11:36:59

How to make Link from react-router scroll to div?

There is a regular menu with a couple of links. Some of them lead to separate pages, and the rest should scroll to the desired div on the page.
Menu items are rendered like this:

renderNav() {
    return menu.map((item, index) => {

      return (
        <li className='menu-item' key={index}>
          <Link to={`${item.link}`} className="menu-link" activeClassName="menu-link--is_active">{item.name}</Link>
        </li>
      )
    })
  }

How to beat Link? Only ugly crutches come to mind, but I don’t want to use them

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita Gushchin, 2015-10-29
@iNikNik

1. If you have complex logic: Link accepts the state property , through it you can pass an identifier where to scroll, for example.
Then subscribe to history :

let unlisten = history.listen(location => {
  console.log(location.state); // <-- переданный в Link state.
})

Then, in any way known to you, scroll to the desired element.
But I would strongly advise you not to go beyond the anchors (hash at the end of the url) with regards to navigation.
Link takes a hash property, which can also be obtained by subscribing to history
<Link  to="some" hash="#idOfElement" >Scroll to</Link>

let unlisten = history.listen(location => {
  console.log(location.hash); // <-- переданный в Link hash.
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question