Isaac Sekamatte
Isaac Sekamatte

Reputation: 5598

How to handle a button press inside react-navigation titlebar

I am pretty new to react-native and I am currently handling navigation for my app using react-navigation. I want to be able to add a button to my app's title bar created by react-navigation and be able to press a button to call a function.

static navigationOptions = ({ navigation }) => {
    const { params } = navigation;
    return {
      title: 'Assign To',
      headerRight: (
        <Button
          title='Back'
          onPress={() => params.handlePress()}
        />
      ),
    };
 };

This is close to what I read from the react-navigation docs, but it I keep getting an error of undefined is not an object.

componentDidMount() {
    this.props.navigation.setParams({ handlePress: () =>   this.myFunction.bind(this) });
}

I have myFunction defined inside my component as follows

myFuntion() {
    //...
}

Any help is highly appreciated

Upvotes: 0

Views: 367

Answers (2)

Frits
Frits

Reputation: 106

For most elements you can use the onPress() function in react-native

onPress={() => { Alert.alert("You clicked me") } }

If you need to bind you can usually do it with the following example:

onPress={this.functionName.bind(this)}

Upvotes: 0

sinewave440hz
sinewave440hz

Reputation: 1365

I'm going to answer this, with a little more explanation. The problem as you know was that you were combining the syntax of two similar approaches. You can use either the .bind syntax: handlePress: this.myFunction.bind(this) or the so-called fat-arrow syntax: handlePress: () => this.myFunction. They are more-or-less equivalent and there are opinions that the fat-arrow syntax supersedes the bind syntax (and, as always, opinions to the contrary :) ). There are differences, such as (quoting from this):

  • Arrow functions are always anonymous, which means you can't, for instance, reliably call them recursively (since you don't have a reliable lexical name to use).
  • Arrow functions actually create lexical bindings for this, super, and arguments. Only this is bound by .bind(..).
  • Arrow functions cannot be used in new expressions, while bind(..) bound functions can.

Also, given that this is a react native question, it might help to be aware of this interesting article:

https://medium.freecodecamp.org/why-arrow-functions-and-bind-in-reacts-render-are-problematic-f1c08b060e36

Upvotes: 1

Related Questions