FormidableLabs / react-swipeable

React swipe event handler hook
https://commerce.nearform.com/open-source/react-swipeable
MIT License
1.99k stars 146 forks source link

Using it on multiple elements ? #250

Closed PC-Poro closed 3 years ago

PC-Poro commented 3 years ago

Hi,

I'm looking forward to use this to replicate Apple Mail's behavior : swiping on

(or
  • in my case) to see action to the corresponding row.

    Actually, when attributing the handlers to every row, it fires only for the last one. Here's my simplified code.

    `import { useSwipeable } from 'react-swipeable

    function Mail() { const handlers = useSwipeable({ onSwipedLeft: () => console.log('delete')}) return (

      {mailList.map((mail, index) => { return ( <li {...handlers} key={index} id={index}> )})} }

      export default Mail ` I feel like this should be pretty obvious but I can't find any corresponding instructions in the documentation, nor in the closed issues.

      Thank you.

  • hartzis commented 3 years ago

    @PoroWCI Thank you for the issue and highlighting this. I'm actually surprised it hasn't come up before. It had previously been on my mind when developing the hook a year ago, but since no one had ever requested or mentioned this capability I didn't research it too much.

    I did some initial exploration and came up with a sensible solution. Essentially make each item(li) an indi component and setup individual handlers per item.

    import { useSwipeable } from "react-swipeable";
    
    const ListItem = ({ onDelete }) => {
      const handlers = useSwipeable({
        onSwipedLeft: () => onDelete(),
      });
      return (<li {...handlers} />
    }

    I tried to setup a very basic example that works with this approach, let me know what you think:

    PC-Poro commented 3 years ago

    It's working great. Exactly what I needed. Thank you for your great work!