Home > Software engineering >  React Navigation, Please attach a method to this component
React Navigation, Please attach a method to this component

Time:12-15

I am trying to navigate to a route using onPress, but get the error: Please attach a method to this component I need the whole component clickable, button and text - is that possible?

<TouchableOpacity
  style={styles.widgetCont}
  onPress={() => navigate(AppRoutes.Settings.Name)}
>
  <Text style={styles.widgetText}>{setupRemindersDescription}</Text>
  <Button
    title={setupRemindersLabel}
    buttonStyle={[buttons.primarySpace, styles.widgetBTN]}
    titleStyle={buttons.smallTitle}
  />
</TouchableOpacity>

This doesnt give me the error and navigates fine:

  <TouchableOpacity
    style={VehicleStyles.widgetCont}
    onPress={async () => {
      const success = await tryBiometrics();
      if (success) {
        Linking.openURL(BookRepairUrl);
      }
    }}
  >
    <Button
      title={myVehicles.booknow}
      buttonStyle={[buttons.primarySpace, VehicleStyles.widgetBTN]}
      titleStyle={buttons.smallTitle}
    />
  </TouchableOpacity>

CodePudding user response:

I need the whole component clickable, button and text - is that possible?

for that you can use Pressable from react-native.

CodePudding user response:

To make the entire TouchableOpacity component clickable, you can wrap the Text and Button components inside the TouchableOpacity component with a View component and apply the onPress event handler to the View component instead.

Here is an example of how you can modify your code to make the entire TouchableOpacity component clickable:

<TouchableOpacity
  style={styles.widgetCont}
>
  <View onPress={() => navigate(AppRoutes.Settings.Name)}>
    <Text style={styles.widgetText}>{setupRemindersDescription}</Text>
    <Button
      title={setupRemindersLabel}
      buttonStyle={[buttons.primarySpace, styles.widgetBTN]}
      titleStyle={buttons.smallTitle}
    />
  </View>
</TouchableOpacity>
  • Related