I'm trying to create a component that has a minHeight, but can scale if it's content get larger. Its content is a row containing an icon text (Idea is that when icon size is slightly bigger it wouldn't immediately increase the height of the component).
First image below shows how it should look like and how it's displayed on the web, but on iOS and android it doesnt work as expected. Seems like the height of the view doesn't scale properly and instead keeps a fixed size the icon will make it break boundries.
Try for yourself: https://snack.expo.dev/ZBTGBMLa9
How it should look like (and how it's displayed in the webview)
How it actually looks like on iOS and android
Code from this component
import * as React from 'react';
import { Text, View, StyleSheet, Image } from 'react-native';
export default function TestComp({text, logo}) {
return (
<View style={styles.container}>
<View style={styles.content}>
{logo && <Image style={styles.logo} source={require('../assets/snack-icon.png')} /> }
<Text>
{text}
</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
minHeight: 50,
marginVertical: 10,
alignItems: 'center'
},
content: {
padding: 10,
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'green',
},
logo: {
height: 28,
width: 28,
marginRight: 8,
},
});
CodePudding user response:
as the container
has marginVertical: 10
and content
has padding: 10
, you can add style to the text to be with maxWidth
of Dimensions.get('window').width - 40
(if there's logo decrease another 36)
import * as React from 'react';
import { Text, View, StyleSheet, Image, Dimensions } from 'react-native';
export default function TestComp({text, logo}) {
return (
<View style={styles.container}>
<View style={styles.content}>
{logo && <Image style={styles.logo} source={require('../assets/snack-icon.png')} /> }
<Text style={[styles.text, logo ? styles.textWithLogo : {}]}>
{text}
</Text>
</View>
</View>
);
}
const windowWidth = Dimensions.get('window').width
const styles = StyleSheet.create({
container: {
minHeight: 50,
marginVertical: 10,
alignItems: 'center'
},
content: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'green',
},
logo: {
height: 28,
width: 28,
marginEnd: 8,
marginStart: 10,
marginVertical: 10
},
text: {
maxWidth: windowWidth - 40,
marginEnd: 10,
marginStart: 10,
marginVertical: 10
},
textWithLogo: {
maxWidth: windowWidth - 76,
marginStart: 0
}
});
and indeed RN has still work to do :/
(also notice I removed padding
from content and used margin
on logo and text instead, for avoiding android cut height text)
CodePudding user response:
Just give the Text
this style:
js <Text numberOfLines={1} style={{maxWidth: '90%'}} >