Arpith Siromoney 💬

Using flex to center content

I’m building an app to share notes called Constellational, and a big part of it is creating a pleasant environment to read and write in. I’ve found that keeping track of the post length helps me write better, so when you swipe the keyboard down to read your post a word count shows up in the navigation bar.

The navigation bar has a button on the left (to go back), a title in the middle (the word count) and also says Post (or Update) on the right. Since the left and right buttons are of unequal sizes, this meant the word count wasn’t centered. Fixing this using flex is straightforward:

var styles = StyleSheet.create({
  navBar: {
    flexDirection: ‘row’
  },
  left: {
   flex: 1
  },
  right: {
    flex: 1,
    alignItems: 'flex-end'
  },
  title: {
    textAlign: 'center'
  }
});

This sets the sizes of the left and right buttons to be equal, which in turn makes the word count stay centered (with a little help from textAlign). Note that this fixes #53.