diff --git a/src/demo/index.jsx b/src/demo/index.jsx index d73c89bc..16702d6f 100644 --- a/src/demo/index.jsx +++ b/src/demo/index.jsx @@ -153,6 +153,12 @@ class Demo extends Component { isInputNum={isInputNum} shouldAutoFocus value={otp} + onFocus={(e, i) => { + console.log('focused>>>', e, i); + }} + onBlur={(e) => { + console.log('blurred>>>', e); + }} />
diff --git a/src/lib/index.jsx b/src/lib/index.jsx index a14becb4..9ac56b7f 100644 --- a/src/lib/index.jsx +++ b/src/lib/index.jsx @@ -10,6 +10,8 @@ const DELETE = 46; type Props = { numInputs: number, onChange: Function, + onFocus: Function, + onBlur: Function, separator?: Object, containerStyle?: Object, inputStyle?: Object, @@ -252,9 +254,29 @@ class OtpInput extends Component { onPaste={this.handleOnPaste} onFocus={e => { this.setState({ activeInput: i }); + const { onFocus } = this.props; + e.target.select(); + + const { relatedTarget } = e; + // If the previous focus was another child input don't call onFocus + if (relatedTarget && this.container.contains(relatedTarget) && relatedTarget.tagName.toLowerCase() === 'input') { + return; + } + + onFocus && onFocus(e, i); + }} + onBlur={(e) => { + this.setState({ activeInput: -1 }); + const { onBlur } = this.props; + + const { relatedTarget } = e; + // If the blur is other input that is part of the OTP don't call onBlur + if (relatedTarget && this.container.contains(relatedTarget) && relatedTarget.tagName.toLowerCase() === 'input') { + return; + } + onBlur && onBlur(e); }} - onBlur={() => this.setState({ activeInput: -1 })} separator={separator} inputStyle={inputStyle} focusStyle={focusStyle} @@ -282,6 +304,7 @@ class OtpInput extends Component { isStyleObject(containerStyle) && containerStyle )} className={!isStyleObject(containerStyle) ? containerStyle : ''} + ref={container => this.container = container} > {this.renderInputs()}