Skip to content

Commit 0dae010

Browse files
committed
✨ shouldAutoFocus
1 parent d70115f commit 0dae010

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

README.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,13 @@ export default class App extends Component {
101101
<td>none</td>
102102
<td>Style applied to each input when disabled.</td>
103103
</tr>
104+
<tr>
105+
<td>shouldAutoFocus</td>
106+
<td>boolean</td>
107+
<td>false</td>
108+
<td>false</td>
109+
<td>Auto focuses input on inital page load.</td>
110+
</tr>
104111
</table>
105112

106113
## Development

src/docs/index.jsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ class Demo extends Component {
103103
disabled={isDisabled}
104104
onChange={this.handleOtpChange}
105105
separator={<span>{separator}</span>}
106+
shouldAutoFocus
106107
/>
107108
</div>
108109
<button

src/lib/index.jsx

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ type Props = {
1616
focusStyle?: Object,
1717
disabled?: boolean,
1818
disabledStyle?: Object,
19+
shouldAutoFocus?: boolean,
1920
};
2021

2122
type State = {
@@ -26,24 +27,28 @@ type State = {
2627
class SingleOtpInput extends PureComponent<*> {
2728
input: ?HTMLInputElement;
2829

30+
// Focus on first render
31+
// Only when shouldAutoFocus is true
2932
componentDidMount() {
3033
const {
3134
input,
32-
props: { focus },
35+
props: { focus, shouldAutoFocus },
3336
} = this;
3437

35-
if (input && focus) {
38+
if (input && focus && shouldAutoFocus) {
3639
input.focus();
3740
}
3841
}
3942

40-
componentDidUpdate() {
43+
componentDidUpdate(prevProps) {
4144
const {
4245
input,
4346
props: { focus },
4447
} = this;
4548

46-
if (input && focus) {
49+
// Check if focusedInput changed
50+
// Prevent calling function if input already in focus
51+
if (prevProps.focus !== focus && (input && focus)) {
4752
input.focus();
4853
input.select();
4954
}
@@ -89,6 +94,7 @@ class OtpInput extends Component<Props, State> {
8994
numInputs: 4,
9095
onChange: (otp: number): void => console.log(otp),
9196
disabled: false,
97+
shouldAutoFocus: false,
9298
};
9399

94100
state = {
@@ -199,6 +205,7 @@ class OtpInput extends Component<Props, State> {
199205
separator,
200206
disabled,
201207
disabledStyle,
208+
shouldAutoFocus,
202209
} = this.props;
203210
const inputs = [];
204211

@@ -223,6 +230,7 @@ class OtpInput extends Component<Props, State> {
223230
isLastChild={i === numInputs - 1}
224231
disabled={disabled}
225232
disabledStyle={disabledStyle}
233+
shouldAutoFocus={shouldAutoFocus}
226234
/>
227235
);
228236
}

0 commit comments

Comments
 (0)