Improving modal close with escape and backspace

This commit is contained in:
Maxime Lalo 2023-05-10 15:27:26 +02:00
parent 4dedba4744
commit d9a05c017a

View File

@ -79,16 +79,35 @@ export default class Modal extends React.Component<IProps, IState> {
willClose: false, willClose: false,
}); });
}, this.props.animationDelay); }, this.props.animationDelay);
document.body.style.overflow = "auto";
} }
if (prevProps.isOpen !== this.props.isOpen && this.props.isOpen) { if (prevProps.isOpen !== this.props.isOpen && this.props.isOpen) {
this.setState({ isOpen: true }); this.setState({ isOpen: true });
document.body.style.overflow = "hidden";
} }
this.rootRefElement.current?.style.setProperty("--animation-delay", this.props.animationDelay!.toString().concat("ms")); this.rootRefElement.current?.style.setProperty("--animation-delay", this.props.animationDelay!.toString().concat("ms"));
} }
public override componentDidMount(): void {
document.addEventListener("keydown", this.handleKeyDown);
}
public override componentWillUnmount(): void {
document.body.style.overflow = "auto";
document.removeEventListener("keydown", this.handleKeyDown);
}
protected close() { protected close() {
if (this.props.hasContainerClosable === false) return; if (this.props.hasContainerClosable === false) return;
if (this.state.willClose) return; if (this.state.willClose) return;
this.props.onClose(); this.props.onClose();
} }
private handleKeyDown = (e: KeyboardEvent): void => {
if (e.key === "Escape" || e.key === "Esc" || e.key === "Backspace") {
this.props.onClose();
}
}
} }