Skip to content

Commit

Permalink
fix: correctly initializes the component
Browse files Browse the repository at this point in the history
Now the component will initialize itself also in the presence of missing `items`

Closes #3
  • Loading branch information
CloudPower97 committed Dec 3, 2018
1 parent 623a17d commit b64ca67
Showing 1 changed file with 23 additions and 29 deletions.
52 changes: 23 additions & 29 deletions src/Scrollspy.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,14 @@ export default class Scrollspy extends Component {

this.setState(
{
elementsToSpy: items.map(item => document.getElementById(item)),
navItems: items.map(
item =>
document.querySelector(`[href="#${item}"]`) ||
document.querySelector(`[href="/#${item}"]`)
),
elementsToSpy: items.map(item => document.getElementById(item)).filter(item => item),
navItems: items
.map(
item =>
document.querySelector(`[href="#${item}"]`) ||
document.querySelector(`[href="/#${item}"]`)
)
.filter(item => item),
},
() => {
this.createIntersectionObserver()
Expand All @@ -53,14 +55,10 @@ export default class Scrollspy extends Component {
}

createMutationObserver = () => {
const { items } = this.props

new MutationObserver((mutations, observer) => {
if (items.every(item => document.getElementById(item))) {
this.getElements()
this.getElements()

observer.disconnect()
}
observer.disconnect()
}).observe(document.body, {
childList: true,
subtree: true,
Expand All @@ -71,20 +69,18 @@ export default class Scrollspy extends Component {
const { elementsToSpy, navItems } = this.state
const { options, intersectionRatio: ratio } = this.props

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)
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)
})
}

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

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

render() {
Expand Down

0 comments on commit b64ca67

Please sign in to comment.