Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Stack Navigation With Class Component [duplicate]

I am currently building a react native app and am using a stack navigator to navigate between the screens in my app. In my App.js, I am currently storing the screens in this format:

const Stack = createStackNavigator();

export default function App() {
  return (
      <NavigationContainer>
        <Stack.Navigator initialRouteName="screen1">
          <Stack.Screen name="screen1" component={Screen1}></Stack.Screen>
          <Stack.Screen name="screen2" component={Screen2}></Stack.Screen>
        </Stack.Navigator>
      </NavigationContainer>
  );
}

After the user is in screen 1, I want to be able to navigate to screen 2 on the press of a button. I read through the documentation and I only saw examples on how to do this with functional components, for example:

function Screen1({ navigation }) {
  return (
    <View>
      <Button title="Go to Home" onPress={() => navigation.navigate('screen2')} />
    </View>
  );
}

But how can I do this with a class component:

class Screen1 extends Component {

    render() {
        return(
            <View>
               // This does not work because I do not know how to pass in the navigation object
               <Button title="Go to Home" onPress={() => navigation.navigate('screen2')} />
            </View>
        )
    }
}

Where do I pass in the { navigation } ?

like image 511
Questions123 Avatar asked Apr 20 '26 01:04

Questions123


1 Answers

You dont have to pass navigation, its passed as a prop.

You can access it like below

this.props.navigation.navigate('nextScreen')
like image 153
Guruparan Giritharan Avatar answered Apr 21 '26 15:04

Guruparan Giritharan



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!