In React-TSX, e: React.KeyboardEvent<HTMLInputElement>
doesn’t expose e.target.value
for me to check the current input value.
const handleDateKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
// this does NOT work
if (e.target.value ... ) // e.target.value does not exist
}
My problem is, I need to add automatic dashes to a Phone field after the 3rd and 6th digit, which is done in React.ChangeEvent
as below, but this code prevents Backspacing because you get stuck at e.g. the 6th digit if you backspace from a complete number like 111-222-3333:
const handlePhoneChange = (e: React.ChangeEvent<HTMLInputElement>) => {
let value = e.target.value;
if (/^[0-9]{3}$/.test(value) || /^[0-9]{3}-[0-9]{3}$/.test(value)) {
value += '-';
}
setPhone(value);
}
So I tried to go the KeyboardEvent
route, and there I can check for whether Backspace was pressed, but I can’t check the current e.target.value
to apply my regex expression:
const handlePhoneKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
// Automatically add dashes if Key is NOT Backspace
// Doesn't work because no e.target.value
if (e.key !== 'Backspace' && (/^[0-9]{3}$/.test(e.target.value) || /^[0-9]{3}-[0-9]{3}$/.test(value)))
}
So how would I both auto-add dashes by checking the current value against a regex, AND be able to skip that behavior depending on whether Backspace was pressed?