PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 17, 2022

[FIXED] Why Text element doesn't center vertically inside View?

 November 17, 2022     react-native, reactjs, text, vertical-alignment     No comments   

Issue

Using react-native, I created a custom button as follows:

import React, {Component, Fragment} from 'react';

import globalStyles from './../../globals/styles'

import {
    Text,
    View,
    TouchableOpacity,
    StyleSheet
} from 'react-native';

export default class MyButton extends Component {
    render() {
        return (
            <TouchableOpacity style={styles.opacitySurface} onPress={this.props.customAction}>
                <View style={styles.textContainer}>
                    <Text style={styles.text}>{this.props.buttonText}</Text>
                </View>
            </TouchableOpacity>
        )
    }
}

let buttonFontSize = 10;

const styles = StyleSheet.create({
        textContainer: {
            justifyContent: 'center',
            alignItems: 'center',
        },
        opacitySurface: {
            backgroundColor: globalStyles.colors.customerGreen,
            width: "25%",
            height: 60,
            padding: 10,
            borderRadius: 10,
            shadowColor: '#000',
            shadowOffset: { width: 0, height: 0 },
            shadowOpacity: 0.8,
            shadowRadius: 1.5
        },
        text: {
            textAlign: 'center',
            fontFamily: globalStyles.fonts.OpenSans,
            color: 'white',
            fontSize: buttonFontSize,
        }
    }
);

But the text inside this button doesn't align vertically. Premise: I am new in react-native and I am almost sure I missing something of really stupid.

enter image description here


Solution

For the properties justifyContent and alignItems to work they need to be on an element with display: flex.

Whats making your text align to center is the property textAlign: 'center' on style.text

Use display: 'flex' and flex: 1 on your style.textContainer

textContainer: {
    display: 'flex'
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
}


Answered By - Lucas Fabre
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing