From ff0daabca2478b91a1dd3b8faeac7a8ff5496fea Mon Sep 17 00:00:00 2001 From: Marcus Sander Date: Fri, 16 Jun 2023 11:18:38 +0200 Subject: [PATCH 1/2] feat: onFocus & onBlur events --- src/index.tsx | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/index.tsx b/src/index.tsx index de05ad6..4cd325e 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -28,6 +28,10 @@ interface OTPInputProps { value?: string; /** Number of OTP inputs to be rendered */ numInputs?: number; + /** Callback to be called when the OTP has lost focus */ + onBlur?: () => void; + /** Callback to be called when the OTP has received focued */ + onFocus?: (index: number) => void; /** Callback to be called when the OTP value changes */ onChange: (otp: string) => void; /** Function to render the input */ @@ -51,6 +55,8 @@ const isStyleObject = (obj: unknown) => typeof obj === 'object' && obj !== null; const OTPInput = ({ value = '', numInputs = 4, + onBlur, + onFocus, onChange, renderInput, shouldAutoFocus = false, @@ -117,10 +123,18 @@ const OTPInput = ({ const handleFocus = (event: React.FocusEvent) => (index: number) => { setActiveInput(index); event.target.select(); + + if (!inputRefs.current.includes(event.relatedTarget as HTMLInputElement)) { + onFocus?.(index); + } }; - const handleBlur = () => { + const handleBlur = (event: React.FocusEvent) => { setActiveInput(activeInput - 1); + + if (!inputRefs.current.includes(event.relatedTarget as HTMLInputElement)) { + onBlur?.(); + } }; const handleKeyDown = (event: React.KeyboardEvent) => { From 02cfb6b950af51c0c5131c7e8d45c5fe5b2049eb Mon Sep 17 00:00:00 2001 From: Marcus Sander Date: Fri, 16 Jun 2023 12:58:32 +0200 Subject: [PATCH 2/2] docs: Document onBlur & onFocus --- README.md | 15 +++++++++++++++ example/src/App.tsx | 2 ++ 2 files changed, 17 insertions(+) diff --git a/README.md b/README.md index 4536338..0e3c1b4 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,21 @@ export default function App() { A function that returns the input that is supposed to be rendered for each of the input fields. The function will get two arguments: inputProps and index. inputProps is an object that contains all the props that should be passed to the input being rendered (Overriding these props is not recommended because it might lead to some unexpected behaviour). index is the index of the input being rendered. + + + onBlur + function + false + none + Called when OTP has lost focus + + + + onFocus + function + false + none + Called when OTP has received focus. The index of the input gaining focus is passed as the first argument onChange diff --git a/example/src/App.tsx b/example/src/App.tsx index 9fd11d7..bad1acb 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -107,6 +107,8 @@ function App() {

Enter verification code

console.log('OTP gained focus!')} + onBlur={() => console.log('OTP lost Focus!')} inputStyle="inputStyle" numInputs={numInputs} onChange={handleOTPChange}