minwork / use-long-press

React hook for detecting click (or tap) and hold event
MIT License
120 stars 12 forks source link

How can I pass an argument to onCancel from {...bind} ? #17

Closed kamzata closed 2 years ago

kamzata commented 3 years ago

I have some code like this. I'd like to intercept the single click and tap, and the long click e long press .

So, I thought to remove onClick={() => start(preset)} from the button and call start(preset) from shortPress function. But how can I pass the preset argument as well?

const Presets = ({presetsList: presets, presetStart: start}) => {

    const longPress = () => {
          console.log('long click or long press');
          // Some other code... 
    }

    const shortPress = event => {
        console.log('single click or tap')
       // start(preset)
    }

    const bind = useLongPress(longPress, {onCancel: shortPress} )

    return (
        <section onContextMenu={(e)=> e.preventDefault()}>
            {presets.map( preset => {
                return <button 
                            key={presets.indexOf(preset)} 
                            onClick={() => start(preset)} 
                            {...bind} 
                            type="button" 
                        >
                            <span>{preset.time}</span>
                        </button>
            })}
        </section>
    )
}

export default Presets;

Basically, I'd need to pass an argument to onCancel callback from {...bind}. Is there a way to do it?

minwork commented 2 years ago

That's a really good use case that's need to be handled internally. I will work on implementing that, but for the time being you can make a workaround and append preset to event data passed to onMouseUp onMouseLeave and onTouchEnd in order to extract it in onCancel (note that you need to set option captureEvent to true) like this:

onMouseUp={(event) => {
  // Not sure it will actually work that way, but worth a try
  event.preset = preset;
  return bind.onMouseUp(event);
}}
onMouseLeave={...}
onTouchEnd={...}

and then in onCancel

onCancel: (event) {
  const preset = event.preset;
}
github-actions[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

minwork commented 2 years ago

@kamzata Addressed in #23