Skip to content

Commit

Permalink
fix: now handling some edge cases
Browse files Browse the repository at this point in the history
Correctly handling href like `/#my-hash`

Preventing crash when `navItems` doesn't get initialized correctly

Closes #1
  • Loading branch information
CloudPower97 committed Dec 3, 2018
1 parent 462c2ea commit 4903a8c
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions src/Scrollspy.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ export default class Scrollspy extends Component {
this.setState(
{
elementsToSpy: items.map(item => document.getElementById(item)),
navItems: items.map(item => document.querySelector(`[href="#${item}"]`)),
navItems: items.map(
item =>
document.querySelector(`[href="#${item}"]`) ||
document.querySelector(`[href="/#${item}"]`)
),
},
() => {
this.createIntersectionObserver()
Expand All @@ -67,18 +71,20 @@ export default class Scrollspy extends Component {
const { elementsToSpy, navItems } = this.state
const { options, intersectionRatio: ratio } = this.props

const observer = new IntersectionObserver(entries => {
entries.forEach(({ isIntersecting, intersectionRatio, target }) => {
if (isIntersecting && intersectionRatio > ratio) {
this.removeActiveClass()
this.addActiveClass(navItems.find(navItem => navItem.href.includes(target.id)))
}
if (navItems.every(navItem => navItem)) {
const observer = new IntersectionObserver(entries => {
entries.forEach(({ isIntersecting, intersectionRatio, target }) => {
if (isIntersecting && intersectionRatio > ratio) {
this.removeActiveClass()
this.addActiveClass(navItems.find(navItem => navItem.href.includes(target.id)))
}
})
}, options)

elementsToSpy.forEach(elem => {
observer.observe(elem)
})
}, options)

elementsToSpy.forEach(elem => {
observer.observe(elem)
})
}
}

addActiveClass = el => {
Expand All @@ -91,8 +97,10 @@ export default class Scrollspy extends Component {
const { navItems } = this.state
const { activeClass } = this.props

const active = navItems.find(navItem => navItem.classList.contains(activeClass))
active && active.classList.remove(activeClass)
if (navItems.every(navItem => navItem)) {
const active = navItems.find(navItem => navItem.classList.contains(activeClass))
active && active.classList.remove(activeClass)
}
}

render() {
Expand Down

0 comments on commit 4903a8c

Please sign in to comment.