I am trying to vertically center Text in a TouchableOpacity but it is hard to get it done for me.
My 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 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",
},
});
Currently I set alignSelf
in buttonTitle as 'center' but I have also tried:
And many other ways I could find on Google but none of them worked. It only centers the Text horizontally. Can anyone help me with vertically centering Text of this TouchableOpacity component?
Thanks in advance!
Have a try by using textAlign: 'center'
in the style of the text component.
also, you can refer to the official docs from here.
Problem solved:
React Native's default direction is column
which is different than the web.
Thus, what I needed is to add justifyContent: "center"
within the button
styles, so the code looks like:
const styles = StyleSheet.create({
button: {
justifyContent: "center",
alignItems: "center",
borderRadius: 4,
width: 240,
height: 100,
backgroundColor: "#FFF",
marginBottom: 12,
},
buttonTitle: {
fontSize: 24,
color: "#fff",
fontWeight: "bold",
},
});
Hope it helps those who encounter the same problem!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.