Skip to content

Instantly share code, notes, and snippets.

@pomle
Last active October 25, 2017 10:13
Show Gist options
  • Save pomle/dc028be96aa6aa1abf084cdf1c49935d to your computer and use it in GitHub Desktop.
Save pomle/dc028be96aa6aa1abf084cdf1c49935d to your computer and use it in GitHub Desktop.
import React from 'react';
class MyComponent extends React.Component {
constructor() {
super();
this.handleMouseMove = scrollMiddleWare()(scroll => {
this.setState({
movement: scroll.abs.x,
});
});
}
componentDidMount() {
window.addEventListener('mousemove', this.handleMouseMove);
}
componentWillUnmount() {
window.removeEventListener('mousemove', this.handleMouseMove);
}
render() {
return (
<div onMouseMove={this.handleMouseMove} />
)
}
}
@JustFly1984
Copy link

JustFly1984 commented Oct 25, 2017

import React, { Component } from 'react'

class MyComponent extends Component {
    // this is babel Stage-0 preset stuff, so you don't need constructor anymore, and you can assign methods with `=`
    state = {
        movement: 
    }
    handleMouseMove = scrollMiddleWare()(scroll => {
        // setState is async, so you better cache abs.x, or you could get `scroll` undefined, and blow up the stack
        const movement = scroll.abs.x
        this.setState(
          // yes, you can get arguments)
          (prevState, props) => ({
            movement
          })
        )
    })

    componentDidMount = () => {
        window.addEventListener('mousemove', this.handleMouseMove);
    }

    componentWillUnmount = () => {
        window.removeEventListener('mousemove', this.handleMouseMove);
    }

    render = () => (
        <div
            onMouseMove={this.handleMouseMove}
        />
    )
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment