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}
/>
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);
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}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With