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