Somename
Somename

Reputation: 3434

Align the Header in center

react-navigation: 1.0.0-beta.11

react: 16.0.0-alpha.12

react-native: 0.47.1

I'm following the ReactNavigation tutorial to render the Header from a passed prop to the screen.

class ChatScreen extends React.Component {
  static navigationOptions = ({ navigation }) => ({
    title: `Chat with ${navigation.state.params.user}`,   // <- Talking bout this
  });
  render() {
    const { params } = this.props.navigation.state;
    return (
      <View>
        <Text>Chat with {params.user}</Text>
      </View>
    );
  }
}

I want the title in title: Chat with ${navigation.state.params.user} to appear in the center. How do I style it? I also want change it's color.

I tried this suggestion but did not work.

Many thanks.

After updating the code, it's aligning to the center but it's not quite the center. It's more to the right. I think it's cause of the arrow to the left, how can I fix it?

enter image description here

Updated Code:

static navigationOptions = ({ navigation }) => ({
    title: `${navigation.state.params.name.item.name}`,
    headerTitleStyle: {
    color: '#000',
    textAlign: 'center',
    alignSelf: 'center'
    }
});

Upvotes: 0

Views: 13442

Answers (3)

MD. Sakib Khan
MD. Sakib Khan

Reputation: 41

According to React Navigation 5.x

you have to use headerTitleAlign to center the title. In android, its value is by default left, and in iOS its value is center.

<Stack.Navigator
  initialRouteName='Welcome'
  screenOptions={{
    headerTitleStyle: {
      color: 'white',
      fontSize: 20,
    },
    headerTitleAlign: 'center',
  }}
>
  <Stack.Screen name='Welcome' component={Welcome}/>
</Stack.Navigator>

More Details: https://reactnavigation.org/docs/stack-navigator/#headertitlealign

Upvotes: 1

Aung Myat Hein
Aung Myat Hein

Reputation: 4178

If your screen has headerLeft or Back button,

headerTitleStyle: {
  textAlign: "center",
  alignSelf: "center"
}

is not enough to make center title.
You have to use headerRight: (<View></View>) to appear at center.

 static navigationOptions = {
    headerTitleStyle: {
      textAlign: "center",
      alignSelf: "center"
    }
    headerRight: <View><View />
  };

Upvotes: 2

Khurram
Khurram

Reputation: 695

titleStyle property has been rename to headerTitleStyle You can now style you header title via headerTitleStyle by passing it to navigation options.

....
headerTitleStyle: {
      color: 'color value',
      textAlign: 'center',
      alignSelf: 'center' //if style using flexbox
}
....

Upvotes: 1

Related Questions