devfolioco / react-otp-input

:heavy_check_mark: OTP Input Component for React

Home Page:http://devfolioco.github.io/react-otp-input

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use onKeyDown?

AnkitDhoot opened this issue · comments

How can I use onKeyDown feature in this component for submitting the 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

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)}
            />
          )}

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

commented

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