Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we center title of react-navigation header?

React-navigation docs are still young, and reading through the issues is not working quite much for me (changes on each version) does anyone have a working method to center title in Android using react-navigation in React Native?

like image 567
jsdario Avatar asked Apr 10 '17 15:04

jsdario


People also ask

How do I center header title in react navigation?

Navigator> <MainStack. Screen name="home" component={HomeScreen} options={{ title: "Home Title", // Center the header title on Android headerTitleAlign: "center", }} /> </MainStack.

How do I center text in React Native?

To center text with React Native, we can use flexbox-like styles. to set flex to 1 to expand the View to fit the screen. And we use justifyContent to 'center' to center horizontally and alignItems to center vertically. Then we put our text in the Text component.


2 Answers

Warning: react-navigation changes a lot, the way to do title align, already changed for like 2-3 times from my first answer of it.

If my answer doesn't work for you, please see other answers.

Modified 2021/08/31:

In year of 2020, headerLayoutPreset was also deprecated. The new way is via defaultNavigationOptions: (@ThatFrenchComputerGuy's answer helped me)

const AppNavigator = createStackNavigator({     Home: { screen: HomeScreen },  },   {   defaultNavigationOptions: {       title: 'Aligned Center',       headerTitleAlign: 'center'   } }); 

Modified 2019/03/12:

In year of 2018, after react-navigation v2 release (7 Apr 2018), for some reason alignSelf was not working anymore. Here it is the new working way, using headerLayoutPreset. from @HasanSH:

const HomeActivity_StackNavigator = createStackNavigator({     Home: {screen: Main}, }, {headerLayoutPreset: 'center'}); 

Original Answer 2017/07/11:

Use headerTitleStyle:

static navigationOptions = {     headerTitleStyle: { alignSelf: 'center' },     title: 'Center Title', } 

enter image description here

like image 64
Val Avatar answered Sep 22 '22 12:09

Val


As of 2021, you can use headerTitleAlign.

Although headerLayoutPreset technically works, it should display a message informing that it is deprecated for expo users. The implementation is as follows:

const AppNavigator = createStackNavigator({     Home: HomeScreen,  },   {   defaultNavigationOptions: {       title: 'Centered',       headerTitleAlign: 'center'   } })

React-Navigation v5.x Update: As per @Ewan ' s rectification, if you are using React-Navigation v5.x, you cannot pass parameters to createStackNavigator(). Therefore, you should implement it as follows:

<Stack.Navigator screenOptions={{headerTitleAlign: 'center'}}> 

Here is an image of it working

like image 36
ThatFrenchComputerGuy Avatar answered Sep 23 '22 12:09

ThatFrenchComputerGuy