kud
5/3/2017 - 4:36 PM

<AnchorLink /> — A react component to handle anchor links with a better animation (and without unfocusing the current element!)

— A react component to handle anchor links with a better animation (and without unfocusing the current element!)

import React  from 'react'
import smoothScroll from 'smoothscroll-polyfill'
smoothScroll.polyfill()

export const scrollTo = (id, opt = { behavior: 'smooth' }) => {
  document.querySelector(`#${id}`).scrollIntoView({
    behavior: opt.behavior
  })

  history.pushState(null, null, `#${id}`)
}

class AnchorLink extends React.Component {
  static defaultProps = {
    behavior: 'smooth'
  }

  handleClick = (e) => {
    e.preventDefault()

    const id = e.target
      .getAttribute('href')
      .substring(1)

    scrollTo(id, {
      behavior: this.props.behavior
    })
  }

  render() {
    return (
      <a className={this.props.className} href={this.props.href} onClick={this.handleClick}>{this.props.children}</a>
    )
  }
}

export default AnchorLink