Home > OS >  React Navigation - Right button function
React Navigation - Right button function

Time:09-17

I have a Navigation:

const MessageStack = createStackNavigator();
const MessageNavigator = () => (
<MessageStack.Navigator>
    <MessageStack.Screen name="Messages" component={MessagesScreen} />
    <MessageStack.Screen 
        name="Chat" 
        component={ChatScreen} 
        options={({ route }) => ({
            title: route.params.thread.username,
            headerRight: () => (
                <Text style={{paddingEnd:10}} onPress={}>View Profile</Text>
            ),
        })} 
    />
</MessageStack.Navigator>

)

My chatScreen:

function ChatScreen({ route }) {

const { thread } = route.params
const [messages, setMessages] = useState([]);

const createTwoButtonAlert = () =>
Alert.alert(
  "Alert Title",
  "My Alert Msg",
  [
    {
      text: "Cancel",
      onPress: () => console.log("Cancel Pressed"),
      style: "cancel"
    },
    { text: "OK", onPress: () => console.log("OK Pressed") }
  ]
);

From the rightButton in the nav bar:

headerRight: () => (
    <Text style={{paddingEnd:10}} onPress={}>View Profile</Text>
),

I want to call the function in my chatScreen createTwoButtonAlert and make the alert appear.

CodePudding user response:

There is an example on the react-native-navigation website.

In this example, you define the headerRight property within the Screen component instead of the router component.

function ChatScreen ({ route, navigation }) {

  const { thread } = route.params
  const [messages, setMessages] = useState([]);

  useLayoutEffect(() => {
    const createTwoButtonAlert = () => {
      Alert.alert(
        'Alert Title',
        'My Alert Msg',
        [
          {
            text: 'Cancel',
            onPress: () => console.log('Cancel Pressed'),
            style: 'cancel'
          },
          { text: 'OK', onPress: () => console.log('OK Pressed') }
        ]
      );
    };

    navigation.setOptions({
      headerRight: () => (
        <Text onPress={() => createTwoButtonAlert()}>View Profile</Text>
      ),
    });
  }, [navigation]);
}

CodePudding user response:

You can specify the headerRight property in your ChatScreen itself with the help of navigation.setOptions()

function ChatScreen ({ route, navigation }) {
 
 React.useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <Text style={{ paddingEnd: 10 }} onPress={createTwoButtonAlert}>
          View Profile
        </Text>
      ),
    });
  }, [navigation]);

  const createTwoButtonAlert = () =>
    Alert.alert('Alert Title', 'My Alert Msg', [
      {
        text: 'Cancel',
        onPress: () => console.log('Cancel Pressed'),
        style: 'cancel',
      },
      { text: 'OK', onPress: () => console.log('OK Pressed') },
    ]);

  return (
    //your view
  );
};

Check this Live snack

  • Related