diff --git a/README.md b/README.md index 4536338..68949e7 100644 --- a/README.md +++ b/README.md @@ -129,6 +129,13 @@ export default function App() { false Auto focuses input on initial page load. + + shouldRemoveWhiteSpaceOnPaste + boolean + false + false + Removes white spaces from pasted OTP characters. + ### ⚠️ Warning @@ -152,6 +159,8 @@ The v3 of `react-otp-input` is a complete rewrite of the library. Apart from mak - A new prop called `inputType` has been added to the component. This prop can be used to specify the type of the input that will be passed to the input element being rendered. The default value of this prop is `number`. +- An new prop called `shouldRemoveWhiteSpaceOnPaste` has been added to the component. This prop can be used to disallow spaces as valid OTP characters. This is default set to `false`. + ## Migrating from v1 `react-otp-input` is now a controlled component to facilitate functionalities that weren't possible before from the application using it, such as clearing or pre-assigning values. For `v1.0.0` and above, a `value` prop needs to be passed in the component for it to function as expected. diff --git a/example/src/App.tsx b/example/src/App.tsx index 9fd11d7..77d3029 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -116,6 +116,7 @@ function App() { inputType={inputType} renderInput={(props) => } shouldAutoFocus + shouldRemoveWhiteSpaceOnPaste />
diff --git a/src/index.tsx b/src/index.tsx index de05ad6..4f6151a 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -44,6 +44,8 @@ interface OTPInputProps { inputStyle?: React.CSSProperties | string; /** The type that will be passed to the input being rendered */ inputType?: AllowedInputTypes; + /** Boolean to not consider spaces as valid OTP values */ + shouldRemoveWhiteSpaceOnPaste?: boolean; } const isStyleObject = (obj: unknown) => typeof obj === 'object' && obj !== null; @@ -59,6 +61,7 @@ const OTPInput = ({ placeholder, containerStyle, inputStyle, + shouldRemoveWhiteSpaceOnPaste = false, }: OTPInputProps) => { const [activeInput, setActiveInput] = React.useState(0); const inputRefs = React.useRef>([]); @@ -183,9 +186,14 @@ const OTPInput = ({ const otp = getOTPValue(); let nextActiveInput = activeInput; + let pastedString = event.clipboardData.getData('text/plain'); + + if (shouldRemoveWhiteSpaceOnPaste) { + pastedString = pastedString.replace(/\s/g, ''); + } + // Get pastedData in an array of max size (num of inputs - current position) - const pastedData = event.clipboardData - .getData('text/plain') + const pastedData = pastedString .slice(0, numInputs - activeInput) .split('');