0

I am learning React Native Web. I've been trying to center text on my web page, I've tried many suggestions from various posts but the text "my name is...His name is..." remains stuck to the top left corner of the web page no matter which properties I add/change in the container. The button, on the other hand, is centered.

Thanks for your help

Code

import React, { useState } from "react"
import { StyleSheet, Text, View, Button } from "react-native"

export default function App() {
    const [name, setName] = useState('Joe');
    const [person, setPerson] = useState({ name: 'mario', age: 40})

    const clickHandler = () => {
        setName('chun-li');
        setPerson({name: 'luigi', age: 45})
    }   

    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <Text >My name is {name}</Text>
                <Text >His name is {person.name} and his age is {person.age}</Text>
            </View>
            <View style={styles.buttonContainer}>
                <Button title='update state' onPress={clickHandler}/>
            </View> 
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
        textAlign: 'center',
        textAlignVertical: 'center',
        alignSelf: 'center',
    },

    buttonContainer: {
        alignItems: 'center',
    },

    header: {
        backgroundColor: 'green',
        alignSelf: 'center',
        justifyContent: "flex-start",
        alignItems: 'center',
        top: 0
    }
});
NickyLarson
  • 115
  • 1
  • 2
  • 18
  • Why is container positioned absolutely? That makes it's dimensions basically 0 without top/right/bottom/left properties. – zero298 Jan 20 '20 at 17:37
  • I didn't realise that. I was trying out various things and I have just left all of those things in the container to show the various properties I tried. I didn't use them all at once. I have removed position: 'absolute' and the issue remains – NickyLarson Jan 20 '20 at 17:50

1 Answers1

0

First of all, you need to change

<View styles={styles.container}>
<View styles={styles.header}>

to

<View style={styles.container}>
<View style={styles.header}>

Finally add style changes according to your requirements

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        alignItems: 'center',
        justifyContent: 'center',
    },
    buttonContainer: {
        alignItems: 'center',
    },
    header: {
        backgroundColor: 'green',
        justifyContent: "center",
        alignItems: 'center',
    }
});

Hope this helps you. Feel free for doubts.

SDushan
  • 4,341
  • 2
  • 16
  • 34