Search code examples
react-nativereact-native-iosreact-navigation-v5

How to trigger class function using button in react navigation 5 header?


I have this class component below. I need to trigger a function in my class from the navigation header. Nothing happens when I click 'TEST'. If I replace this.triggerFunction with console.log("TEST") or something then it works.

https://reactnavigation.org/docs/header-buttons here documentation gives an example for functional component but I cannot find anything about class one.

class Home extends React.Component {
   ...


  async componentDidMount() {
    ...
    
    this.props.navigation.setOptions({
      headerRight: () => (
        <View>
          <TouchableOpacity onPress={() => this.triggerFunction}>
            <Text>TEST<Text>
          </TouchableOpacity>
        </View>
      ),
    });
  }

   
    triggerFunction = () => {
      console.log('inside header function');
    };
  }

Solution

  • import React from 'react';
    import {View, TouchableOpacity, Text} from 'react-native';
    
    class Home extends React.Component {
        async componentDidMount() {
            this.props.navigation.setOptions({
                headerRight: () => {
                    return (<View>
                                <TouchableOpacity onPress={this.triggerFunction}>
                                    <Text>TEST<Text>
                                </TouchableOpacity>
                            </View>
                            );
                  }
            });
          }
    
      triggerFunction = () => {
        console.log('inside header function');
      };
    }