Skip to content

When any of the OTP inputs gets focus call the onFocus callback with the #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/demo/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}}
/>
</div>
<div className="btn-row">
Expand Down
25 changes: 24 additions & 1 deletion src/lib/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const DELETE = 46;
type Props = {
numInputs: number,
onChange: Function,
onFocus: Function,
onBlur: Function,
separator?: Object,
containerStyle?: Object,
inputStyle?: Object,
Expand Down Expand Up @@ -252,9 +254,29 @@ class OtpInput extends Component<Props, State> {
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}
Expand Down Expand Up @@ -282,6 +304,7 @@ class OtpInput extends Component<Props, State> {
isStyleObject(containerStyle) && containerStyle
)}
className={!isStyleObject(containerStyle) ? containerStyle : ''}
ref={container => this.container = container}
>
{this.renderInputs()}
</div>
Expand Down