score:0

Accepted answer

so here is one possible solution to solve this

function usekeypress(targetkey) {
  // state for keeping track of whether key is pressed
  const [keypressed, setkeypressed] = usestate(false);
  // if pressed key is our target key then set to true
  function downhandler(e) {
    if (e.key === targetkey) {
      setkeypressed(true);
      e.preventdefault();
    }
  }
  // if released key is our target key then set to false
  const uphandler = (e) => {
    if (e.key === targetkey) {
      setkeypressed(false);
    }
  };
  // add event listeners
  useeffect(() => {
    window.addeventlistener("keydown", downhandler);
    window.addeventlistener("keyup", uphandler);
    // remove event listeners on cleanup
    return () => {
      window.removeeventlistener("keydown", downhandler);
      window.removeeventlistener("keyup", uphandler);
    };
  }, []); // empty array ensures that effect is only run on mount and unmount
  return keypressed;
}

export function useui() {
  const scrolldistance = 15;
  const arrowup = usekeypress("arrowup");
  const arrowdown = usekeypress("arrowdown");

  const k = usekeypress("k"); // up
  const j = usekeypress("j"); // down

  const w = usekeypress("w"); // up
  const s = usekeypress("s"); // down

  useeffect(() => {
    if (!(arrowup || arrowdown || k || j || w || s)) {
      return null;
    }
    const scrolldirection = arrowup || k || w ? 1 : -1;
    let animationframe = 0;
    let callback = () => {
      const pos = window.pageyoffset;
      window.scroll(0, pos - scrolldistance * scrolldirection);
      animationframe = requestanimationframe(callback);
    };
    animationframe = requestanimationframe(callback);

    return () => {
      cancelanimationframe(animationframe);
    };
  }, [arrowup, arrowdown, k, j, w, s]);

  return null;
}


Related Query

More Query from same tag