Search code examples
javascriptreactjsreact-spring

react-use-gesture useScroll not detecting scroll event


I am trying to use the react-use-gesture library, but can't even seem to get some simple hooks working. I'm trying to use the useScroll hook (eventually to get an animation running with react-spring), but when I bind it to my component, nothing happens.

import { useScroll} from 'react-use-gesture';

function App() {
    const bind = useScroll((e) => {
        e.scrolling ? console.log("I'm being scrolled") : console.log("I'm not being scrolled");

    });
    return (
        <div className="App" {...bind()}>
            // All of my other components in App
        </div>
    );
}

export default App;

I have a feeling I'm missing something obvious. Does anyone have any ideas?


Solution

  • Oddly enough, I wasn't able to get the useScroll hook to work either, but the useWheel hook works just fine.

    import React from "react";
    import { useWheel } from "react-use-gesture";
    import "./styles.css";
    
    export default function App() {
      const wheel = useWheel(state => {
        console.log("wheeling", state.wheeling);
      });
      return (
        <div className="App" {...wheel()}>
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }
    

    Edit vibrant-night-mrb6f

    Was curious as to why scroll events weren't getting picked up but the mouse events were. Maybe this sheds a bit of light on the matter.

    EDIT

    Was able to get the scrolling working by passing optional config object, in this case, setting the DOM target to window. According to Options explained it is recommended to use an effect hook versus spreading in as a prop (though it worked in the codesandbox spread in).

    export default function App() {
      const scroll = useScroll(state => {
        console.log("scrolling", state.scrolling);
      }, {
        domTarget: window,
      });
    
      useEffect(scroll, [scroll]);
    
      return (
        <div className="App" >
          <h1>Hello CodeSandbox</h1>
          <h2>Start editing to see some magic happen!</h2>
        </div>
      );
    }