Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a text in the screen with react native

I am trying to center a text vertically and horizontally on the screen. This is my code

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.header}>
         <Text> Header </Text>
         </View>
         <Text style={styles.text}> some text in the middle center of the screen </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
        backgroundColor:'white',
        alignItems:'center',
        justifyContent:'center'
    },
     header: {
        backgroundColor: 'green',
        alignSelf: 'stretch',
        alignItems: 'center',
        heigth: 80 // this dose not change the header height
    },
  text:{
      //flex: 1,
      justifyContent:'center',
  }
});

If I add the flex:1 to text, the header will also be centered which is not expected. I don't know if it's related but the I am also not able to modify the header view height. How can I solve this? The problems can be reproduced on this snack.

<div data-snack-id="S1urACbJM" data-snack-platform="ios" data-snack-preview="true" data-snack-theme="light" style="overflow:hidden;background:#fafafa;border:1px solid rgba(0,0,0,.16);border-radius:4px;height:505px;width:100%"></div>
<script async src="https://snack.expo.io/embed.js"></script>
like image 701
user567 Avatar asked Nov 09 '17 13:11

user567


People also ask

How do I center text vertically react native?

To put a Text component vertically and horizontally center of View component in RN we have to use justifyContent: 'center' and alignItems: 'center' layout styles.

How do you align items in Center in react native?

Syntax: alignItems: stretch|center|flex-start|flex-end|baseline; Property Values: stretch: It is the default value of alignItems.


1 Answers

This is one way to center text in the screen:

<View style={{
    flex: 1, 
    alignItems: 'center',
    justifyContent: 'center', 
    backgroundColor: 'blue'
}}>
    <Text style={{backgroundColor: 'red'}}>
        Your Text
    </Text>
</View>

And you can also try with position:'absolute':

<View style={{
    backgroundColor: 'blue',
    position: 'absolute', 
    top: 0, left: 0, 
    right: 0, bottom: 0, 
    justifyContent: 'center', 
    alignItems: 'center'}}>
<Text style={{backgroundColor: 'red'}}> Your Text </Text>
</View>

Your centered text

like image 102
Hernán Albertario Avatar answered Oct 20 '22 22:10

Hernán Albertario