Search code examples
javascriptreactjswebmaterial-uilong-press

How handle long press event in react web


everyone! I use react and material ui library. I want to handle click event and long-press event separately. I think problem related to async set state, but for now, I don't know how to handle this events

const [isCommandHandled, setIsCommandHandled] = React.useState(null);
const handleButtonPress = function (e) {
    setIsCommandHandled(false);
    console.log('ON_MOUSE_DOWN ' + isCommandHandled); // here value null
    buttonPressTimer = setTimeout(handleLongPress, 1500, e);
  }.bind(this);

  const handleLongPress = (e) => {
    if (!isCommandHandled) {
      setIsCommandHandled(true);
      console.log('TIMER_IS_EXECUTED' + isCommandHandled); //Here value false or null
      // some other logic for long press event
    }
    clearTimeout(buttonPressTimer);
  };

  const handleButtonRelease = function (e) {
    if (!isCommandHandled) {//isCommandHandled isn't updated here, as a result logic is executed always
       // got regular click, not long press
       // specific logic
      setIsCommandHandled(true);
    }
    clearTimeout(buttonPressTimer);
  };

<IconButton 
             onMouseDown={(e) => handleButtonPress(e)}
             onMouseUp={(e) => handleButtonRelease(e)}
          >
    ```


Solution

  • You can use setState with callback and put the set timeout ID to state:

     setIsCommandHandled((prevState)=>{ 
            console.log("TIMER_IS_EXECUTED" + isCommandHandled); //Here value false or null
            return true; });
    

    Working Example: https://codesandbox.io/s/material-demo-gc0le