devYuraKim / react

udemy - jonas schmedtmann
0 stars 0 forks source link

Re11-worldwise > src > pages > AppLayout | Backspace key problem #22

Closed devYuraKim closed 2 months ago

devYuraKim commented 2 months ago

The Backspace key triggers navigation even when I'm editing text in an input or textarea field!

  useEffect(
    function () {
      function useBackspace(e) {
        if (e.code === "Backspace") navigate(-1);
      }

      document.addEventListener("keydown", useBackspace);

      return () => document.removeEventListener("keydown", useBackspace);
    },
    [navigate]
  );
devYuraKim commented 2 months ago

TL:DR; use document.activeElement with 1)case-insensitive 2)tag comparison

  1. point1: document.activeElement returns the element itself, not a name or a tag.
  2. point2: document.activeElement.tagName returns the tag name in all capital letters. With a lowercase string, the comparison will fail.
useEffect(
    function () {
      function useBackspace(e) {
        const activeElement = document.activeElement.tagName.toLowerCase();
        if (
          activeElement !== "textarea" &&
          activeElement !== "input" &&
          e.code === "Backspace"
        )
          navigate(-1);
      }

      document.addEventListener("keydown", useBackspace);

      return () => document.removeEventListener("keydown", useBackspace);
    },
    [navigate]
  );