How to make this all Stack Screen having just 1 styling, because all of them are having a same style. As you can see. Options Props having a headerStyle, headerTitleStyle, headerLeft, headerTitleAlign have a same value.
This is my file App.js
const MainNavigator = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="MainScreen">
<Stack.Screen
name="MagicScreen"
component={MagicScreen}
options={{
title: 'Magic',
headerStyle: {
backgroundColor: '#0074C4',
},
headerTitleStyle: {
color: 'white',
fontSize: 24
},
headerLeft: null,
headerTitleAlign: 'center',
}}
/>
<Stack.Screen
name="FightingStyleScreen"
component={FightingStyleScreen}
options={{
title: 'Fighting Style',
headerStyle: {
backgroundColor: '#0074C4',
},
headerTitleStyle: {
color: 'white',
fontSize: 24
},
headerLeft: null,
headerTitleAlign: 'center',
}}
/>
<Stack.Screen
name="WeaponScreen"
component={WeaponScreen}
options={{
title: 'Weapons',
headerStyle: {
backgroundColor: '#0074C4',
},
headerTitleStyle: {
color: 'white',
fontSize: 24
},
headerLeft: null,
headerTitleAlign: 'center',
}}
/>
</Stack.Navigator>
</NavigationContainer>
)
};
I tried to find the example code on google. But still don’t find the example :")
2
Answers
Just pass the
screenOptions
prop to theStack.Navigator
component. It defines the default options for each screen in a stack. Something like this will work:You can then change the title for each of the screens separately.
Stack.Navigator
has ascreenOptions
prop that’s very similar to theoptions
prop onStack.Screen
. It can accept a hard-coded object as a value, or a function that returns an object. In your case, the function would be best because it allows you to set the header title based on the current route:If you don’t like the big conditional chain, you could drop the function and just pass an object containing
headerStyle
,headerTitleStyle
,headerLeft
, andheaderTitleAlign
. Then you’d set the title in the options of each screen like you’re currently doing.Alternatively, you could create an object to function as a route name map:
And in your
screenOptions
function, settitle
torouteNameMap[route.name] || "Default"