How to use onKeyDown?
AnkitDhoot opened this issue · comments
Ankit Dhoot commented
How can I use onKeyDown feature in this component for submitting the OTP?
Prateek Surana commented
onKeyDown
event is used by the library for performing certain actions with the inputs. Although you can open a PR to also call the onKeyDown
passed by the consumer with the library's onKeyDown
sean commented
My encounter:
Firefox will still allow alphabets even with inputType set to number
.
It wouldn't be the best solution, however a workaround for me to override the package's keyDown function:
- to disabled invalid character
- to apply logic used by the package.
export const blockInvalidChar = (e, keydownFunction) => {
if (e.key.match(/^[^\n]{1}$/)) { // Matching single character
['e', 'E', '+', '-'].includes(e.key) && e.preventDefault(); // Prevent number processors
e.key.match(/^[a-zA-Z]|[^\w\s]$/) && e.preventDefault(); // Prevent alphabets & symbol
}
keydownFunction(e); // Execute package's onKeydown function
};
....
<OtpInput
value={otp}
onChange={setOtp}
numInputs={6}
renderSeparator={false}
shouldAutoFocus={true}
inputType={'number'}
renderInput={(props) => (
<input
{...props}
type="number"
pattern={'/[^0-9]/g'}
className={`otp-input ${FAStyles.optInput}`}
onKeyDown={(e) => blockInvalidChar(e, props.onKeyDown)}
/>
)}
Prateek Surana commented
sean commented
Cool. @prateek3255 It would be nice without have to tempered the used onKeyDown
explicitly. Thanks!