React.js callback function in higher order component for dom events

I am writing a react component and would like to factor out all the dom event listener logic. Currently I have a higher order component (hoc) withDomEvent with listeners attached to the window:

const withDomEvent = (Component) => 

    class WithDomEvent extends React.Component {

        componentDidMount(){
            window.addEventListener('resize', this.onResize)
        }


        componentWillUnmount() {
            window.removeEventListener('resize', this.onResize);
        }

        /**
            I would like to pass in the function that runs on the event
        */
        onResize = (e,f) => {
            console.log(`hoef resize `)
            f(e)
        }

        render(){

            const fn = {
                  onScroll : this.onScroll
                , onResize : this.onResize
            }

            return ( <Component {...this.props} domFn={fn} />)
        }
    }


export default withDomEvent;    

Then I would like to call the function onResize with a call back in the child component, for example:

class FrontPage extends Component {

     doSomethingOnResize = () => {
          this.props.domFn.onResize(e => {
              console.log('ideally I can just do this but there's error')
          })
     }

}

export default withDomEvent(FrontPage)

The error I get is:

withDomEvent.js:35 Uncaught TypeError: f is not a function
at WithDomEvent._this.onResize (withDomEvent.js:35)

This is because f is undefined. So how would I pass in a callback to onResize in WithDomEvent?

1 answer

  • answered 2018-07-11 03:49 Luis Gurmendez

    I think you should have to add the eventListenrs in the components