Reputation: 609
I currently have a simple legend component that produces an output like so:
The problem is that I manually set the height
for the blue rectangle to be as tall as the text. Is there any way I can tell that View to just expand naturally based on the height of the text instead of having to manually set some number as the height
?
You can try out the Snack or check out the code:
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
class App extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={styles.legend}>
<View style={styles.item}>
<View style={styles.shape} />
<View>
<Text>Food</Text>
<Text>25%</Text>
</View>
</View>
<View style={styles.item}>
<View style={styles.shape} />
<View>
<Text>Utilities</Text>
<Text>35%</Text>
</View>
</View>
<View style={styles.item}>
<View style={styles.shape} />
<View>
<Text>Misc.</Text>
<Text>40%</Text>
</View>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
marginHorizontal: 50,
},
legend: {
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between'
},
item: {
flexDirection: 'row',
alignItems: 'center'
},
shape: {
backgroundColor: 'blue',
width: 15,
height: 30, // I DONT WANT TO HAVE TO DO THIS
marginRight: 5
}
});
export default App;
Any help would be appreciated, thanks!
Upvotes: 2
Views: 2949
Reputation: 3703
A complete example to achieve that.
<View style={{flexDirection:'row'}}>
<View style={{flex:1, flexDirection:'row', alignItems:'center'}}>
<View style={{width: 10, backgroundColor:'blue', height:'100%'}} />
<View>
<Text>Food</Text>
<Text>25%</Text>
<Text>25%</Text>
<Text>25%</Text>
</View>
</View>
<View style={{flex:1, flexDirection:'row', alignItems:'center'}}>
<View style={{width: 10, backgroundColor:'blue', height:'100%'}} />
<View>
<Text>Utilities</Text>
<Text>35%</Text>
</View>
</View>
<View style={{flex:1, flexDirection:'row', alignItems:'center'}}>
<View style={{width: 10, backgroundColor:'blue', height:'100%'}} />
<View>
<Text>Misc.</Text>
<Text>40%</Text>
</View>
</View>
</View>
Upvotes: 0
Reputation: 3548
If i understand correctly, firstly you should wrap your each item with a view and after that you should add a second view with flexGrow.
<View>
<View style={{flexGrow: 1}}/>
<View style={styles.item}>
The first view helps you for changing the flexDirection to column and second view which has flexGrow helps you to push down your blue shape. And you should set shape height to 100%.
shape: {
backgroundColor: 'blue',
width: 15,
height: "100%", //here
marginRight: 5,
}
Also i edited your snack code and save it. Link: https://snack.expo.io/HkZ3a5q-V
Upvotes: 0
Reputation: 36
You can use height: '100%' on the shape style, and all the shapes will have the max height of the text
Upvotes: 1