Reputation: 393
I want my header in my react navigation bar to be clickable and have a menu pop up when I click up, I am trying to first just get a log or alert to pop up, but it opens when the screen renders not when I click on it
Here is a link, where I have added a custom component to the header with an onPress but it only fires onRender
https://snack.expo.io/r10TGyieE
What am I doing wrong?
Upvotes: 2
Views: 1248
Reputation: 243
If you would like to avoid making a custom header component, an easy hack is to just add a HeaderLeft component, absolute position it, and then stretch it out 3 times longer than it's original width which is meant to be 1/3 of the screen.
<MyNavStack.Screen
name="MyScreen"
// @ts-ignore
component={MyListScreen}
options={({ navigation, route }) => ({
headerLeft: () => (
<>
// This is the box that is a touchable opacity
<TouchableOpacity
style={{
position: "absolute",
height: "100%",
width: "300%",
}}
onPress={Keyboard.dismiss}
></TouchableOpacity>
// This is my menu icon. The menu icon will take precedence
<TouchableOpacity
style={styles.headerButtonContainerLeft}
onPress={() => {
navigation.openDrawer();
Keyboard.dismiss();
}}
>
<MenuIcon/>
</TouchableOpacity>
</>
),
// ...The rest of the options
Upvotes: 0
Reputation: 1007
your onPress event is not binding so it will trigger at first while you run your application.
when using Es6 arrow function your function is bind by default.onPress={()=>this.someFunction()}
otherwise you need to do bind manually onPress={this.someFunction.bind(this)}
to invoke your function.
class LogoTitle extends React.Component {
render() {
return (
<TouchableOpacity onPress={()=>alert('test')}>
<Text style={{ color: "white", fontWeight:'bold' }}> List Layout</Text>
</TouchableOpacity>
);
}
}
Upvotes: 1
Reputation: 1576
as Tarreq said you can use that
or else
onPress={this.someAction}
as onPress method call a function so you can direct write function name.
Upvotes: 0
Reputation: 1365
just like Dadsquatch said,
This:
onPress={this.someAction()}
is considered as direct code, and it got executed once app reaches the line where it is located (that is why its executed at startup, although you didn't mention it at startup)
But when your use:
onPress={() => this.someAction()}
you telling the compiler that, this is the function to be executed when onPress occurs. And you can see that it is an arrow function format.
Upvotes: 1
Reputation: 566
https://snack.expo.io/HJvXPJix4
You need to have it call onPress={() => this.someAction()}
instead of onPress={this.someAction()}
Upvotes: 1