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!