I have an react native app that fetch data from an api in this api there are news each of it contain subject, picture and details I have problem in set the height of each item to auto height I tried to set the height of container to 100 then the subject and details are just overlapping above each other so I set it to 300 and it's okay for the items that have long text but the problem with the items that have short text so the space between these items become too large so how can I set the height auto so I each item will have height regarding to it's content
so this is the class of each item:
import React, { Component } from "react"
import { View, Image, Text, StyleSheet } from "react-native"
export default class Item extends Component {
render() {
let { item } = this.props;
const { subject, picture, details } = item;
return (
<View style={styles.container}>
<Image style={styles.picture} resizeMode="cover" source={{ uri: picture }} />
{console.log(image)}
<View style={styles.content}>
<Text style={styles.subject}>{subject}</Text>
<Text style={styles.details}>{details}</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
height: 300,
flexDirection: "row",
flex: 1,
padding: 10
},
content: {
flexDirection: "column",
flex: 1
},
picture: {
height: 70,
width: 100
},
subject: {
marginLeft: 20,
fontSize: 16,
fontWeight: 'bold'
},
details: {
marginLeft: 20,
fontSize: 16,
}
})
In react-native, to set the dynamic width and height to a component, we use built-in interface Dimensions. it takes the dimension of a given component and then sets the width and height to its equivalent.
The WebView has default styles. If you want to set height, you also need to add flex: 0 , as stated in the documentation: Please note that there are default styles (example: you need to add flex: 0 to the style if you want to use height property). Save this answer.
React Native provides a Dimensions API that can be used to get the width and the height of the window. From there on, you can compute the available height yourself by subtracting the size of the Toolbar and the TabMenu.
Skip giving height to your container, and you will have dynamically required height and also remove height from your image so that it occupies the height of the final container height as per the text being rendered.
Your stylesheet should look like:
const styles = StyleSheet.create({
container: {
flexDirection: "row",
//flex: 1, - remove this as this doesn't make any sense here.
padding: 10
},
content: {
flexDirection: "column",
flex: 1,
paddingLeft: 10, //if you need separation.
},
picture: {
//height: 70, - commenting this will make it automatically ataining height as per your text grows.
width: 100
},
subject: {
marginLeft: 20,
fontSize: 16,
fontWeight: 'bold'
},
details: {
marginLeft: 20,
fontSize: 16,
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With