Search code examples
reactjstouchtouch-event

React clickable elements in touch container


I'm trying to set up a swipeable container with clickable elements. The component is the following:

const SectionBar = (): JSX.Element => {
  const [translatePercent, setTranslatePercent] = useState(0);
  const [x0, setX0] = useState(0);
  const [isMediumOrLarger, setIsMediumOrLarger] = useState(false);

  useEffect(() => {
    const mediaQuery = window.matchMedia("(min-width: 768px)");
    setIsMediumOrLarger(mediaQuery.matches);
    mediaQuery.addEventListener("change", (event) =>
      setIsMediumOrLarger(event.matches)
    );
  }, []);

  const setSnapPercent = (index: number) => {
    console.log(index);
    if (index === 3) {
      setTranslatePercent(index * 10 + 6);
    } else if (index >= 4) {
      setTranslatePercent((index + 1) * 10);
    } else {
      setTranslatePercent(index * 10);
    }
  };

  const swipe: TouchEventHandler<HTMLUListElement> = (
    event: TouchEvent<HTMLUListElement>
  ) => {
    const dx = -(event.changedTouches[0].clientX - x0) / 5;

    const percent = Math.max(0, Math.min(dx, MAX_PERCENT));
    setTranslatePercent(percent);
  };

  return (
    <nav className={classes["section-bar"]}>
      <ul
        className={classes["section-list"]}
        style={
          isMediumOrLarger
            ? {}
            : {
                transform: `translateX(-${translatePercent}%)`,
              }
        }
        onTouchStart={(event) => setX0(event.changedTouches[0].clientX)}
        onTouchEnd={swipe}
        onTouchMove={swipe}
      >
        {Object.entries(createSections).map(([key, value], index) => (
          <li key={key}>
            <Link href={`/create/race#`}>
              <a className={classes.link} onClick={() => setSnapPercent(index)}>
                {value}
              </a>
            </Link>
          </li>
        ))}
      </ul>
    </nav>
  );
};

When I try testing the component out in the simulated phone in Chrome developer tools I can swipe just fine, but tapping on one of the links only seems to register clicks on the links at index 0 and sometimes 1 regardless of which link I press. When I don't pass the touch event props to the ul the links work just fine, so I think the problem has something to do with the touch events.


Solution

  • I got it working. in swipe, I subtracted the change in x from the current transform percent. I have no idea why that fixed it.