Text in TouchableOpacity does not vertically center

Hi, I am trying to learn React Native from scratch again and trying to create a custom button with TouchableOpacity. I tried to follow this example from the documentation: link

But I cannot really get to Text in a TouchableOpacity vertically centered.

I did not change much of App.tsx:

import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, View } from "react-native";

import { CustomButton } from "./src/components/CustomButton";

export default function App() {
  return (
    <View style={styles.container}>
      <CustomButton title="Button" />
      <StatusBar style="auto" />
    </View>
  );
}

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

And here is my CustomButton.tsx:

import React from "react";
import { TouchableOpacity, StyleSheet, Text } from "react-native";

interface CustomButtonProps {
  title: string;
}

export const CustomButton = ({ title }: CustomButtonProps): JSX.Element => {
  return (
      <TouchableOpacity style={styles.button}>
        <Text style={styles.buttonTitle}>{title}</Text>
      </TouchableOpacity>
  );
};

const styles = StyleSheet.create({
  button: {
    borderRadius: 4,
    width: 240,
    height: 100,
    backgroundColor: "#FFF",
    marginBottom: 12,
  },
  buttonTitle: {
    alignSelf: "center",
    fontSize: 24,
    color: "#fff",
    fontWeight: "bold",
  },
});

I tried alignSelf: “center” on the Text component, which is the code above, and I also have tried:

  • textAlign: ‘center’ in Text component,
  • alignItems: ‘center’ in TouchableOpacity,
  • alignItems: ‘center’, justifyContent: ‘center’ in Text component

And many other ways that I found on Google, and asked on StackOverflow as well, but sadly none of solutions works. Can anyone help? Thank you!

Hi.

If I were to guess, it’s probably the following:

On the web, the default direction is row, while in React Native the default direction is column. So try this in the button styles:

justifyContent: "center"

EDIT: I’ve created a snack and it was as I suspected.

const styles = StyleSheet.create({
  button: {
    borderRadius: 4,
    width: 240,
    height: 100,
    backgroundColor: '#FFF',
    marginBottom: 12,
    borderColor: 'orange',
    borderStyle: 'solid',
    borderWidth: 5,
    justifyContent: "center",
    alignItems: "center",
  },
  buttonTitle: {
    fontSize: 24,
    color: '#000',
    fontWeight: 'bold',
  },
});

1 Like

Thank you so much!

1 Like

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.