2

I want to vertically center my text inside a view with an explicit height.

Center text vertically in react-native did not fully answer my question because they don't use explicit height.

When I use

  <View style={styles.rightContainer}>

            <Text style={styles.label2}>
              Centered
            </Text>

        </View>
  rightContainer: {
    marginRight: 10,
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
   label2: {
    height: 40,
    backgroundColor: 'green',
    textAlignVertical: 'center',
  },

result1

If I take away the explicit height,

  label2: {
    backgroundColor: 'green',
    textAlignVertical: 'center',
  },

it works

it works.

I need to set the explicit height because I will convert this View to a tappable button.

How do I make this work? What am I misunderstanding about react-native layout?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
quantumpotato
  • 9,637
  • 14
  • 70
  • 146

1 Answers1

3

It's because the 'textAlignVertical' property is Android-only. Check the documentation on Text.

You could add an extra container wrapping the text:

export default class FlexDirectionBasics extends Component {
  render() {
    return (
      <View style={styles.rightContainer}>
        <View style={styles.labelContainer}>
          <Text style={styles.label}>Centered</Text>
        </View>
      </View>
    );
  }
}

const styles = {
  rightContainer: {
    marginRight: 10,
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  labelContainer: {
    height: 40,
    backgroundColor: 'green',
    alignItems: 'center',
    justifyContent: 'center',
  },
  label2: {},
};
tvanlaerhoven
  • 709
  • 5
  • 15