4

I want to focus on a textinput when I navigate to a new screen. This works when I add a screen to the stack, but not when I go back in the stack.

Instead, the input focuses for a second and blurs immediately.

Here is what I get:

  • Screen A is first in the stack and input blurs immediately
  • Screen B is added to the stack and works as intended

enter image description here

Any idea what is causing this?

FYI, I have the same issue if I use autoFocus.

Here is the whole (pretty straight forward) code:

import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import * as React from "react";
import { TextInput, View, Button, Text } from "react-native";

function ScreenA({ navigation }) {
    const textInputRef = React.useRef();

    const focusOnInput = e => {
        textInputRef.current.focus();
    };

    navigation.addListener("focus", focusOnInput);
    return (
        <View>
            <Text>SCREEN A</Text>
            <TextInput ref={textInputRef} />
            <Button title="Go to screen B" onPress={() => navigation.navigate("ScreenB")} />
        </View>
    );
}

function ScreenB({ navigation }) {
    const textInputRef = React.useRef();

    const focusOnInput = e => {
        textInputRef.current.focus();
    };

    navigation.addListener("focus", focusOnInput);

    return (
        <View>
            <Text>SCREEN B</Text>
            <TextInput ref={textInputRef} />
            <Button title="Go to screen A" onPress={() => navigation.navigate("ScreenA")} />
        </View>
    );
}

const Stack = createStackNavigator();

function TestComp() {
    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen component={ScreenA} name="ScreenA" />
                <Stack.Screen component={ScreenB} name="ScreenB" />
            </Stack.Navigator>
        </NavigationContainer>
    );
}

export default TestComp;
Ryan Pergent
  • 4,432
  • 3
  • 36
  • 78
  • You can add you focusOnInput in the useEffect, also because everytime your time change state it will run `navigation.addListener("focus", focusOnInput);`, but probably I am late to answer you. – Guilherme Felipe Reis Nov 23 '20 at 10:15
  • 1
    Yeah, that's just a test component to show a simple way to create the issue. It still happens if the addListener is inside a useEffect. – Ryan Pergent Nov 23 '20 at 13:12

0 Answers0