I'm creating a custom Header for my Screens and I'm trying to center the route name.
The problem is that there exist another component for my back button and it's making the centering really difficult.
Here is my component;
export default function Header({ navigation }) {
const route = useRoute()
console.log(route)
return (
<SafeAreaView>
<View style={styles.container}>
<TouchableOpacity
style={styles.paddedContainer}
onPress={() => navigation.goBack()}>
<Icon name="left" size={25} color={'black'} />
</TouchableOpacity>
<Text style={styles.routeName}>{route.params.title}</Text>
</View>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
container: {
width: '100%',
flexDirection: 'row',
backgroundColor: '#fff',
paddingBottom: 10,
elevation: 5,
zIndex: 5,
textAlign: 'center',
},
paddedContainer: {
marginLeft: SIZES.width * 0.05,
marginTop: SIZES.height * 0.02,
},
routeName: {
left: '50%',
fontSize: 22,
fontWeight: 'bold',
color: 'black',
marginTop: SIZES.height * 0.02,
},
})
I've tried textAlign, justifyContent, alignContent and all seems to be not working for my example.
CodePudding user response:
First of all, your container need to have display:flex
.
Second, there are two element inside container, so your title cannot be perfectly center.
Considered this, separate the component if you need another behaviour.
Here is the style that you need for center title element, but the <Icon/>
will stay on the right. Play with flex-direction
to make them in the way you want.
const styles = StyleSheet.create({
container: {
width: '100%',
display:'flex',
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: '#fff',
paddingBottom: 10,
elevation: 5,
zIndex: 5,
textAlign: 'center',
},
paddedContainer: {
marginLeft: SIZES.width * 0.05,
marginTop: SIZES.height * 0.02,
},
routeName: {
left: '50%',
fontSize: 22,
fontWeight: 'bold',
color: 'black',
marginTop: SIZES.height * 0.02,
},
})
CodePudding user response:
Please find below Code:
export default function Header({ navigation }) {
const route = useRoute()
console.log(route)
return (
<SafeAreaView style={{flex:1,justifyContent:'center'}}>
<View style={styles.container}>
<TouchableOpacity
style={styles.paddedContainer}
onPress={() => navigation.goBack()}>
<Icon name="left" size={25} color={'black'} />
</TouchableOpacity>
<Text style={styles.routeName}>{route.params.title}</Text>
</View>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
container: {
width: '100%',
display:'flex',
flexDirection: 'row',
justifyContent: 'center',
backgroundColor: '#fff',
paddingBottom: 10,
elevation: 5,
zIndex: 5,
textAlign: 'center',
},
paddedContainer: {
marginLeft: SIZES.width * 0.05,
marginTop: SIZES.height * 0.02,
},
routeName: {
left: '50%',
fontSize: 22,
fontWeight: 'bold',
color: 'black',
marginTop: SIZES.height * 0.02,
},
})
Hope it will work!