Home > OS >  How to pass navigation as a prop in react native?
How to pass navigation as a prop in react native?

Time:12-25

So in the following stack, the screen with the name Chats and component HomeScreen has automatically received the navigation prop and it works

But the other three-screen(Python,Java, & React) have not received it. How to solve this?

export default function App(){

  return (
    <View>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name='Chats' component={HomeScreen} />
          <Stack.Screen name='Python'>{props => <ChatBox text="Python Developer Beta Pvt Ltd" id={1} />}</Stack.Screen>
          <Stack.Screen name='Java'>{props => <ChatBox text="Java Developer Johnson Pvt Ltd" id={0} />}</Stack.Screen>
          <Stack.Screen name='React'>{props => <ChatBox text="React Developer Johnson Pvt Ltd" id={2} />}</Stack.Screen>
        </Stack.Navigator>
      </NavigationContainer>
    </View>
  );
}

CodePudding user response:

You need to explicitly pass the props({...props}).

<Stack.Navigator>
          <Stack.Screen name='Chats' component={HomeScreen} />
          <Stack.Screen name='Java'>{props => <ChatBox text="Java Developer Johnson Pvt Ltd" id={0} {...props} />}</Stack.Screen>
        </Stack.Navigator>
      </NavigationContainer>

CodePudding user response:

import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function MyBackButton() {
  const navigation = useNavigation();

  return (
    <Button
      title="Back"
      onPress={() => {
        navigation.goBack();
      }}
    />
  );
}

You can use useNavigation hook instead of using props.

  • Related