devfolioco / react-otp-input

:heavy_check_mark: OTP Input Component for React
http://devfolioco.github.io/react-otp-input
MIT License
654 stars 424 forks source link

How to use onKeyDown? #352

Open AnkitDhoot opened 2 years ago

AnkitDhoot commented 2 years ago

How can I use onKeyDown feature in this component for submitting the OTP?

prateek3255 commented 1 year ago

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

kahsing commented 1 year ago

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:


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)}
            />
          )}
prateek3255 commented 1 year ago

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

kahsing commented 1 year ago

Cool. @prateek3255 It would be nice without have to tempered the used onKeyDown explicitly. Thanks!