Skip to main content

Header buttons

Now that we know how to customize the look and feel of our headers, let's make them smart! In fact, it might be ambitious, let's just give them the ability to react very clearly to our touch.

Adding a button to the title#

The most common way to interact with a heading is to click the button to the left or right of the heading. Let's add a button to the right side of the header (one of the hardest places to tap on the entire screen, depending on your finger and phone size, but also a normal place to place buttons).

const StackScreen = () => {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{
headerTitle: props => <LogoTitle {...props} />,
headerRight: () => (
<Button
onPress={() => alert('This is a button!')}
title="Info"
color="#fff"
/>
),
}}
/>
</Stack.Navigator>
);
}

Try this example on Snack

When we define our button in this way, the this variable in the options parameters is not an instance of HomeScreen, so you cannot call setState or any instance methods on it. This is very important because very often you want the buttons in your header to interact with the screen that the header belongs to. So, we'll see how to do this next.

How a title interacts with its display component#

To be able to interact with the screen component, we need to use navigation.setOptions to define our button instead of the options property. By using navigation.setOptions inside a screen component, we can access screen properties, state, context, etc.

const StackScreen = () => {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={({ navigation, route }) => ({
headerTitle: props => <LogoTitle {...props} />
})}
/>
</Stack.Navigator>
)
}
const HomeScreen = ({ navigation }) => {
const [count, setCount] = React.useState(0)
React.useLayoutEffect(() => {
navigation.setOptions({
headerRight: () => (
<Button onPress={() => setCount(c => c + 1)} title="Update count" />
),
})
}, [navigation])
return <Text>Count: {count}</Text>
}

Payment#

Now you are on a stripped-down version of the site, after subscribing to Patreon, you will get full access to the training course, as well as access to our server's private channels in Discord.

Download our mobile application or get tested in our JavaScript telegram bot, and also subscribe to our news.

Become a Patron!

Sumerian school

Contributors โœจ#

Thanks goes to these wonderful people (emoji key):


Dmitriy Vasilev

๐Ÿ“–๐Ÿ’ฒ

Become a Patron!