How do you put the processor onKeyPress on the body in react typescript?



  • I want me to open my dropdown on the Enter keyboard. To do that, I understand you need to hang a body processor. How do you do that? I just want to change the state on the true evidence on Enter. Мой dropdoan



  • useEffect Add the event listener document (singing) keydown instead keypress😞

    import { useEffect, useState } from "react";
    

    export default function App() {
    const [isActive, setIsActive] = useState(false);

    const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === "Enter") {
    setIsActive((prev) => !prev);
    }
    };

    useEffect(() => {
    document.addEventListener("keydown", handleKeyDown);
    return () => {
    document.removeEventListener("keydown", handleKeyDown);
    };
    }, []);

    return <div>Press Enter: {isActive ? "active" : "not active"}</div>;
    }

    https://codesandbox.io/s/eager-firefly-c3bnv?file=/src/App.tsx



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2