1

I have a fixed nav I created in React but when I click a link on it the window scrolls too far and the nav covers the top of the content. I have tried to dynamically calculate the height of the nav and take this into consideration in the scroll but it's still going to the wrong position.

import React from 'react'
import { string } from 'prop-types'

class FixedNav extends React.Component {
  constructor(props){
    super(props)

    this.handleClick = this.handleClick.bind(this)
  }

  shouldComponentUpdate (nextProps) {
    return nextProps.navItems !== this.props.navItems
  }

  handleClick (e) {
    const nav = document.querySelector('#fixedNav')
    let navHeight = nav.getBoundingClientRect().height
    let itemLink = document.querySelector(e.target.parentElement.dataset.link)
    let scrollHeight = itemLink.offsetTop - navHeight
    window.scroll(0, scrollHeight)
    window.location.hash = e.target.parentElement.dataset.link
    e.preventDefault()
  }

  createNavItems () {
    const { navItems } = this.props
    return navItems.map((item, key) => {
      const itemLink = items[1].link
      return (
        <li key={key} data-link={itemLink}>
          <a href={itemLink} data-link={itemLink} onClick={this.handleClick}>
            <p>{ items[0] }</p>
          </a>
        </li>
      )
    })
  }

  render () {
    const navItems = this.createNavItems()
    return (
      <div>
        <ul id='side-navigation' className='side-nav'>
          {navItems}
        </ul>
      </div>
    )
  }
}

FixedNav.propTypes = {
  navItems: string.isRequired
}

export default FixedNav
user2953989
  • 2,791
  • 10
  • 36
  • 49
  • offsetTop might give you the wrong value since it's relative to the top of the offsetParent: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop If It's your case solution is here: https://stackoverflow.com/q/5598743/7767157 – Mateusz Staniuk Jun 16 '19 at 21:54

0 Answers0