Reputation: 43
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}
/>
Upvotes: 3
Views: 17092
Reputation: 15713
Focusing the input on onLayout
works like a charm :)
const FieldComponent: FC = () => {
const inputRef = useRef<TextInput>(null);
const onPageLayout = useCallback(() => inputRef.current?.focus(), []);
return (
<View onLayout={onPageLayout} style={{ flex: 1 }}>
<TextInput
inputRef={inputRef}
....
/>
</View>
);
};
Upvotes: 0
Reputation: 550
Based on Jarret's comment (withNavigationFocus is deprecated with V6) and this StackOverflow answer (Can't focus TextInput when navigating to a screen):
import {useFocusEffect} from 'react-navigation/native';
const TestFocus = (props) => {
const textRef = useRef(null);
useFocusEffect(
useCallback(() => {
// When the screen is focused
const focus = () => {
setTimeout(() => {
textRef?.current?.focus();
}, 1);
};
focus();
return focus; // cleanup
}, []),
);
return (
<TextInput
ref={textRef}
/>
)
}
Upvotes: 0
Reputation: 1462
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);
Upvotes: 3
Reputation: 2719
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}
/>
Upvotes: 1