Home > database >  Calling a function from React navigation header (getParam is not a function)
Calling a function from React navigation header (getParam is not a function)

Time:08-14

I have this icon that needs to run a function onLogout in a separate file

First I tried passing navigation param to bottomTab options like so

  <BottomTab.Screen
    name="Settings"
    component={Settings}
    options={(navigation) => ({
      title: "Settings",
      tabBarIcon: () => <Icon name="settings" size={20} color="black" />,
      headerRight: (
        <Icon
          onPress={navigation.getParam('onLogout')}
          style={{ marginRight: 14 }} name="log-out" size={18} color="black" />
      )
    })}
  />

In the settings screen where the function lives I have initialized the function like so

this.props.navigation.setParams({ onLogout: this.onLogout });

I have tried inside componentDidMount and componentWillMount

Also tried to bind it

constructor(props) {
    super(props);
    this.onLogout = this.onLogout.bind(this);
}

TypeError: navigation.getParam is not a function. (In 'navigation.getParam('onLogout')', 'navigation.getParam' is undefined)

At one point the function get executed but without me touching the icon but I changed to this

this.props.navigation.setParams({ onLogout: this.onLogout() });

Since that didn't work I tried writing the options in the file itself

export default class Settings extends React.Component {
    static navigationOptions = ({ navigation }) => {
        return {
            headerRight: (
                <Icon
                    // onPress={navigation.getParam('onLogout')} 
                    style={{ marginRight: 14 }} name="log-out" size={18} color="black" />
            )
        };
    };
    ...

No icon shows up on the screen and nothing works with that method (title, ect...)

CodePudding user response:

Try this :

 <BottomTab.Screen
    name="Settings"
    component={Settings}
    options={(props) => ({
      title: "Settings",
      tabBarIcon: () => <Icon name="settings" size={20} color="black" />,
      headerRight:() =>(
        <Icon
          onPress={()=>props.route.params.onLogout()}
          style={{ marginRight: 14 }} name="log-out" size={18} color="black" />
      )
    })}
  />
  • Related