I'm trying to make it full screen via a button. The button both adds css and creates the effect of pressing f11. I am trying to listen to the moment of pressing the 'Escape' key after the button is pressed(added css and pressed f11), with the eventListener, but I have to press the 'Escape' key 2 times because the eventListener does not work in the first time. How can I solve this situation? I am open to all your suggestions. Thank you.
const handleFullScreen = () => {
if (isFullScreen) {
setIsFullScreen(!isFullScreen);
document.exitFullscreen();
} else {
setIsFullScreen(!isFullScreen);
document.documentElement.requestFullscreen();
}
};
useEffect(() => {
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
setIsFullScreen(isFullScreen);
}
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
Return:
<Button
onClick={() => handleFullScreen()}
style={{ marginRight: 10 }}
isOutline
color='info'>
{t('fullscreen')}
</Button>
<div className={`${isFullScreen ? `fullScreen` : ``}`}>
..
</div>
css:
.fullScreen {
position: absolute;
width: 100%;
height: 100vh;
overflow: hidden;
z-index: 1020;
top: 0;
left: 0;
}