Fix focus bugs on mobile
authorGreg Hurrell <greg@hurrell.net>
Tue, 20 Jun 2017 16:48:42 +0000 (09:48 -0700)
committerGreg Hurrell <greg@hurrell.net>
Tue, 20 Jun 2017 16:48:56 +0000 (09:48 -0700)
Changing the value would cause focus to jump to the last field.

src/Field.react.js

index 4d2efb0ff332894b8c556b3c8ac700afe1a1697e..c6069cdeaa2d05e60aad50bfaa254b19bfbd33f1 100644 (file)
@@ -62,6 +62,7 @@ export default class Field extends React.Component {
     const value = fromValue(props.value, props.base);
     this.state = {
       copySucceeded: false,
+      isActive: false,
       selectionEnd: value.length,
       selectionStart: value.length,
       value,
@@ -69,8 +70,10 @@ export default class Field extends React.Component {
   }
 
   componentDidUpdate(prevProps, prevState) {
-    const {selectionStart, selectionEnd} = this.state;
-    this._input.setSelectionRange(selectionStart, selectionEnd);
+    if (this._isActive) {
+      const {selectionStart, selectionEnd} = this.state;
+      this._input.setSelectionRange(selectionStart, selectionEnd);
+    }
   }
 
   componentWillReceiveProps(nextProps) {
@@ -80,6 +83,14 @@ export default class Field extends React.Component {
     this.setState({value: fromValue(nextProps.value, nextProps.base)});
   }
 
+  _onBlur = event => {
+    this._isActive = false;
+  }
+
+  _onFocus = event => {
+    this._isActive = true;
+  }
+
   _onChange = event => {
     const value = event.currentTarget.value;
     if (this._validate(value)) {
@@ -152,6 +163,8 @@ export default class Field extends React.Component {
         <input
           autoCapitalize="none"
           autoComplete="off"
+          onBlur={this._onBlur}
+          onFocus={this._onFocus}
           onChange={this._onChange}
           onSelect={this._onSelect}
           ref={ref => this._input = ref}