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)};
`;