react-otp-input
react-otp-input copied to clipboard
How to use onKeyDown?
How can I use onKeyDown feature in this component for submitting the OTP?
The feature is vailable in: https://www.npmjs.com/package/react18-input-otp
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
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)}
/>
)}
Hey @kahsing the firefox issue has been fixed with v3.0.2 check #393 for more info, and you should not override the the onKeyDown
prop because it will lead to unexpected behaviours
Cool. @prateek3255 It would be nice without have to tempered the used onKeyDown
explicitly. Thanks!