added useKeyPress hook

This commit is contained in:
Wenszel 2023-12-11 11:21:30 +01:00
parent 8721737897
commit e9cb2e4de9
2 changed files with 18 additions and 12 deletions

View File

@ -2,7 +2,7 @@ import React, { useState, useContext, useEffect, useCallback } from 'react';
import { SocketContext } from '../../../App';
import useInput from '../../../hooks/useInput';
import './NameInput.css';
import Overlay from '../../Overlay/Overlay';
import useKeyPress from '../../../hooks/useKeyPress';
const NameInput = ({ isRoomPrivate, roomId }) => {
const socket = useContext(SocketContext);
@ -14,21 +14,12 @@ const NameInput = ({ isRoomPrivate, roomId }) => {
socket.emit('player:login', { name: nickname.value, password: password.value, roomId: roomId });
}, [socket, nickname.value, password.value, roomId]);
useKeyPress('Enter', handleButtonClick);
useEffect(() => {
socket.on('error:wrongPassword', () => {
setIsPasswordWrong(true);
});
const keyDownHandler = event => {
if (event.key === 'Enter') {
event.preventDefault();
handleButtonClick();
}
};
document.addEventListener('keydown', keyDownHandler);
return () => {
document.removeEventListener('keydown', keyDownHandler);
};
}, [socket, handleButtonClick]);
}, [socket]);
return (
<div className='name-overlay'>

15
src/hooks/useKeyPress.js Normal file
View File

@ -0,0 +1,15 @@
import { useEffect } from 'react';
export default function useKeyPress(targetKey, callback) {
const keyPressHandler = ({ key }) => {
if (key === targetKey) {
callback();
}
};
useEffect(() => {
window.addEventListener('keydown', keyPressHandler);
return () => {
window.removeEventListener('keydown', keyPressHandler);
};
}, []);
}