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