I want to build a box with a list of elements using react native. I want the box to grow as more elements are added and once the box is a tall as the device screen the contents of the box become scrollable. That way I can have a header and footer always on screen.
In other words, I want a container to fit it's contents and if there is more content than will fit on the screen, I want the container to be scrollable.
Is that possible?
Here is a rnplay: https://rnplay.org/apps/KrOk6w
Here's the code I'm using in this example, You can change rowCount
to increase the rows.
var React = require('react-native');
var {
View,
Text,
StyleSheet,
ScrollView,
} = React;
var styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
flexDirection: 'column',
backgroundColor: "blue",
},
contentContainer: {
},
headerContainer: {
padding: 20,
backgroundColor: "#EEE",
},
footerContainer: {
padding: 20,
backgroundColor: "#EEE",
},
rowContainer: {
borderTopWidth: 1,
borderColor: "#EEE",
padding: 30,
backgroundColor: "red",
},
});
class Test extends React.Component {
render() {
var rowCount = 20;
var rows = [];
for(i = 0; i < rowCount; i++) {
rows.push(<View style={styles.rowContainer}>
<Text>
{"Some text"}
</Text>
</View>);
}
return (
<View style={styles.container}>
<View style={styles.headerContainer}>
<Text>
{"Header text"}
</Text>
</View>
<ScrollView
contentContainerStyle={styles.contentContainer}>
{rows}
</ScrollView>
<View style={styles.footerContainer}>
<Text>
{"Footer text"}
</Text>
</View>
</View>
);
}
};
module.exports = Test;
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.
In the ScrollView, we can scroll the components in both direction vertically and horizontally. By default, the ScrollView container scrolls its components and views in vertical. To scroll its components in horizontal, it uses the props horizontal: true (default, horizontal: false).
Hence, to make a scrollable list of data, you also need to put the View component inside the ScrollView component. Note: ScrollView must have a parent with a defined height. The ScrollView is a generic React Native scrolling container that allows both vertical and horizontal direction scrolling.
set a property to the container view of: justify-content: flex-start
Use flexGrow: 0
, otherwise the ScrollView will take all the height available even when there is no content.
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