javascriptreactjsreact-router

Using anchor tags in react-router 4


I want the page to scroll down to my anchor tags when a user navigates to it through an anchor link.

I'm using react-router 4 and I've defined things as follows:

navbar:

export default (props) => {
  const { 
    updateModal,
    updateRoute,
  } = props
  return(
    <Navbar fluid collapseOnSelect>
      <Nav>
        <NavDropdown eventKey="4" title="Solutions" id="nav-dropdown" noCaret>
          <MenuItem eventKey="4.1">
             <Link to='/solution#ipos'>TESTING ANCHOR</Link>
          </MenuItem>
...

some route:

export default class extends Component {
  constructor() {
    super()
    this.state = {
      isLoading: true
    }
  }
  render() {
    return (
      <Grid className='solutions' fluid>
       <Row className='someClass'>
        <div>
          <h2><a href='ipos' id='ipos'>Ipos morna santos paros</a></h2>
          ...

I can see the hash anchor tag in the url and in my redux store when I click on the anchor link in the navebar, and it indeed navigates to the new route, but it doesn't scroll down to the tag itself.

Is it up to me to create the scroll function or how is it supposed to work exactly?


Solution

  • 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';