cocacrave
cocacrave

Reputation: 2633

React add/remove event listener

For some reason this.getVisible() is not firing on scroll/resize events. Can someone tell me what the problem is?

import React, { Component } from 'react'

const ZeroSum = ({
  selector,
  ...passedProps,
}) => WrappedComponent => class WithZeroSum extends Component {
  constructor(props) {
    super(props)
    this.selector = document.querySelector(selector)
    this.state = {
      zeroSum: 0,
    }
  }

  componentWillMount() {
    window.addEventListener('scroll resize', () => this.getVisible())
    this.getVisible()
  }

  componentWillUnmount() {
    window.removeEventListener('scroll resize', () => this.getVisible())
  }

  getVisible() {
    const vHeight = document.documentElement.clientHeight
    const eTop = this.selector.getBoundingClientRect().top
    return this.setState({ zeroSum: Math.max(0, vHeight - eTop) })
  }

  render() {
    const { zeroSum } = this.state
    const props = { ...this.props, ...passedProps }
    console.log(zeroSum)
    return <WrappedComponent {...props} zeroSum={zeroSum} />
  }
}

export default ZeroSum

Upvotes: 0

Views: 1934

Answers (2)

hannad rehman
hannad rehman

Reputation: 4331

constructor(props) {
super(props)
this.selector = document.querySelector(selector)
this.state = {
  zeroSum: 0,
}
  this.getVisible.bind(this) // bind all your class methods to this

}

Upvotes: 0

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

You can't pass multiple event types in it. Try this:

constructor(props) {
    // ...
    this.state = {
        // ...
        listener: this.getVisible.bind(this)
    };
}

componentWillMount(){
    window.addEventListener("scroll", this.state.listener);
    window.addEventListener("resize", this.state.listener);
    this.state.listener();
}

componentWillUnount(){
    window.removeEventListener("scroll", this.state.listener);
    window.removeEventListener("resize", this.state.listener);
}

Upvotes: 2

Related Questions