javascriptcssreactjsreact-nativematerial-design

How can I center the title in Appbar.Header in react-native-paper?


As you can see in the docs, the default positioning for the title in react-native-paper is left-aligned. I've seen multiple questions and answers about how to implement a centered title both for Android Native as well as React Native's StackNavigator, but I am having no luck pulling off the same effect with react-native-paper.

So far I have tried using the style parameter in Appbar.Header to pass in { textAlign: 'center' } or { flexDirection: 'row', justifyContent: 'space-between' }, but nothing seems to work. I'm not very impressed with react-native-paper's lack of documentation on overrides, but I still hope there's a way to do what I'm looking for.

const styles = { header: { textAlign: 'center' }}

<Appbar.Header style={styles.header}>
  <Appbar.Action icon="close" onPress={() => this.close()} />
  <Appbar.Content title={title} />
  <Button mode="text" onPress={() => this.submit()}>
    DONE
  </Button>
</Appbar.Header>

Considering title accept a node, it can be used to display a react component.

How can I force center the title on all devices?


Solution

  • react-navigation allows passing a component for title instead of a string, so we can do the same thing here:

    I wrote an example that accepts a custom title component and can be used wherever we want:

    import * as React from 'react';
    import { Appbar, Button, Text } from 'react-native-paper';
    
    const ContentTitle = ({ title, style }) => (
      <Appbar.Content
        title={<Text style={style}> {title} </Text>}
        style={{ alignItems: 'center' }}
      />
    );
    
    const App = () => (
      <Appbar.Header> 
        <Appbar.Action icon="close" onPress={() => this.close()} />
        <ContentTitle title={'Title'} style={{color:'white'}} />
        <Button mode="text" onPress={() => this.submit()}>
          DONE
        </Button>
      </Appbar.Header>
    );
    
    export default App;
    

    You can check: https://snack.expo.io/r1VyfH1WL