Home > front end >  I want to close the modal when react esc is pressed
I want to close the modal when react esc is pressed

Time:09-22

We are using react and styled-components.
When the button is pressed, the modal(drawer) is displayed from the right.
I want the modal to be closed when the esc button is pressed.
How do I detect that the esc button has been pressed? codesandbox

import Drawer from "./components/Drawer";
import { FunctionComponent, useState } from "react";

const App: FunctionComponent = () => {
  const [isOpen, setIsOpen] = useState(false);
  const onClose = () => {
    setIsOpen(false);
  };
  return (
    <div className="App">
      <button onClick={() => setIsOpen(!isOpen)}>button</button>
      <Drawer isOpen={isOpen} onClose={onClose}></Drawer>
    </div>
  );
};

export default App;
import React from "react";
import styled from "styled-components";

type Props = {
  isOpen: boolean;
  padding?: number;
  children: React.ReactNode;
  onClose: () => void;
  handleKeyDown: () => void;
};

export default (props: Props) => {
  return (
    <>
      <Overlay isOpen={props.isOpen} onClick={props.onClose} />
      <DrawerModal {...props}>{props.children}</DrawerModal>
    </>
  );
};

const DrawerModal = styled.div<Props>`
  position: absolute;
  overflow: scroll;
  top: 0;
  right: 0;
  height: 100vh;
  width: ${({ isOpen }: Props) => (isOpen ? 400 : 0)}px;
  background: blue;
  box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.25);
  transition: 200ms cubic-bezier(0.25, 0.1, 0.24, 1);
`;

const Overlay = styled.div<{ isOpen: boolean }>`
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: ${(props: { isOpen: boolean }) => (props.isOpen ? 0 : -1)};
`;

CodePudding user response:

Use an effect like this to handle keyboard events like this:

useEffect(() => {
  function handleEscapeKey(event: KeyboardEvent) {
    if (event.code === 'Escape') {
      setIsOpen(false)
    }
  }

  document.addEventListener('keydown', handleEscapeKey)
  return () => document.removeEventListener('keydown', handleEscapeKey)
}, [])

The effect declares a function that handle a keydown event and checks if the escape key was pressed. Then it binds that event handler to the document. When the component is removed, it cleans up by removing the event handler from the document.

  • Related