franjuju
franjuju

Reputation: 92

Create a navigation button with a props using react-navigation in React Native

I'm trying to create a component Button that can help me navigate between stacks. I use react-navigation to navigate in the app. The problem is that I have 3 files :

-App.js

<SafeAreaProvider>
  <StatusBar barStyle="dark-content" backgroundColor="#ecf0f1" />
  <NavigationContainer>
    <Stack.Navigator initialRouteName="Accueil">
      <Stack.Screen name="Accueil" component={AccueilScreen} options={{headerShown: false}}/>
      <Stack.Screen name="Progression" component={ProgressionScreen} />
      <Stack.Screen name="Themes" component={ThemesScreen} />
      <Stack.Screen name="Quizz" component={QuizzScreen} />
    </Stack.Navigator>
  </NavigationContainer>
</SafeAreaProvider>

-Accueil.js

function Accueil({ navigation }) {
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content_container}>
        <Image style={styles.logo} source={require('../assets/logo.jpg')} />
        <Button buttonText="Progression" navigation={navigation}/>
      </View>
   </SafeAreaView>
  )
}

-Button.js

export default function Button(props, navigation) {
  return (
    <TouchableOpacity style={styles.button} onPress={() => navigation.navigate(props.buttonText)}>
      <Text style={styles.button_text}>{props.buttonText}</Text>
    </TouchableOpacity>
  )
}

My problem is that I can't make the navigation.navigate works in the Button component whereas it totally work when I put it directly in the Accueil.js file.

Can you help me?

Upvotes: 0

Views: 348

Answers (1)

Poptocrack
Poptocrack

Reputation: 3009

navigation is a part of props from your Button component

export default function Button({ navigation, ...props }) {
  return (
    <TouchableOpacity style={styles.button} onPress={() => navigation.navigate(props.buttonText)}>
      <Text style={styles.button_text}>{props.buttonText}</Text>
    </TouchableOpacity>
  )
}

You could also do it this way:

export default function Button(props) {
  const { navigation } = props
  ...rest of your code

Upvotes: 2

Related Questions