Search code examples
react-nativeexporeact-native-web

React Native Web: how do you center text?


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
    }
});

Solution

  • 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.