I am trying to disable spaces in the input text field using onChange event and react-hooks. I'm saving the email input in state. The function in onChange event dispatches action, passing e.target as its input. However as soon as the dispatch occurs, the input field gets reset. I have tested the input field and it is working fine but when I click the keyboard space button then event.keyCode and event.which gives me undefined value.
import React, {useReducer} from 'react';
const initialState = {
email: ''
};
function reducer(state, action) {
switch (action.type) {
case 'email':
return {
...state,
email: action.payload
};
default:
throw new Error();
}
}
const Login = () => {
const [state, dispatch] = useReducer(reducer, initialState);
const handleChange = (event) => {
if (event.keyCode == 32) {
return false;
}
dispatch({ type: event.target.name, payload: event.target.value.trim() });
}
return (
<div className="container">
<input
type="email"
name="email"
value={state.email}
onChange={handleChange}
placeholder="Enter Email"
/>
</div>
)
}
export default Login;