Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native TextInput Autofocus is not working

I am having two screens in react native app say Screen A Screen B. A textinput is present in Screen A. I have put autofocus true for that and its working initially.

When we navigate from screen A to Screen B , and then navigates back from B-> A, then the textinput autofocus is not working.

Do any one have any soultion for this ??

<TextInput
  style={styles.textInput}
  textStyle={styles.inputTextStyle}
  autoFocus={true}
  placeholder='Enter Code'
  keyboard={'numeric'}
  placeholderTextColor={AppStyles.color.grey}
  value={code}
  onChangeText={this.updateCode}
  underline={false}
/>
like image 202
anju baby Avatar asked Aug 21 '26 10:08

anju baby


2 Answers

That's because the autofocus triggers first time on componentDidMount. To trigger it manually after navigating back from B to A, you've to use withNavigationFocus HOC. So when the user focuses screen A, you can use following code to show keyboard.

import React from 'react';
import { Text } from 'react-native';
import { withNavigationFocus } from 'react-navigation';

class FocusStateLabel extends React.Component {
   componentDidUpdate() {
       if(this.props.isFocused){
           this.inputField.focus();
       }
   }  
   render() {
     return (
       <TextInput
         ref={(input) => { this.inputField = input; }}
         placeholder = "inputField"
       />
     )
  }
}

// withNavigationFocus returns a component that wraps FocusStateLabel and passes
// in the navigation prop
export default withNavigationFocus(FocusStateLabel);
like image 113
Hamza Waleed Avatar answered Aug 23 '26 01:08

Hamza Waleed


The AutoFocus props is only fired when the component is mounted. When you are navigating back to A, if A is still mounted (just hidden), then the autofocus will not work again.

You should use a ref (add a new state, ref here for example), and add a handler, on navigate back from B to A, to fire this.state.ref.focus()

<TextInput
          ref={ref => ref && this.setState({ref})}
          style={styles.textInput}
          textStyle={styles.inputTextStyle}
          autoFocus={true}
          placeholder='Enter Code'
          keyboard={'numeric'}
          placeholderTextColor={AppStyles.color.grey}
          value={code}
          onChangeText={this.updateCode}
          underline={false}
        />
like image 37
TBouder Avatar answered Aug 23 '26 00:08

TBouder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!