I'm building a simple app in React Native that fetches listings from a remote JSON source and displays them on screen.
So far, using the excellent example here, I've managed to get the results to display using the ListView components in rows (i.e. 1 result per row, see screenshot). I need the results to display in a grid, i.e. 3 to 6 items per row, depending on the screen size and orientation.
What is the best way to get these results into a grid? Can I use ListView for this, or is that only for one-per-row results? I've tried playing around with flexbox styles but, since React doesn't seem to accept % values and ListView doesn't accept styles, I haven't yet had any success.
In react native if we want to make GridView then we have to use FlatList component with numColumns={ } prop. In the numColumns prop we would define how many columns we want in a single row. In current tutorial we are only making 2 Columns per row.
A grid layout can be defined as a layout in which components are arranged in form of rows and columns thus providing an easy way of allocating components on user interface without use of positioning and floating values, in order to use react native grid layout we need to include dependency of react native grid.
The GridView is fully responsive and scrollable component layout. Officially there are no specific GridView Component available in react native application, but we can create Grid layout using FlatList Component by specifying numColumns props (example : numColumns={2}) in FlatList Component.
You need to use a combination of flexbox, and the knowledge that ListView wraps ScrollView and so takes on its properties. With that in mind you can use the ScrollView's contentContainerStyle
prop to style the items.
var TestCmp = React.createClass({ getInitialState: function() { var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); var data = Array.apply(null, {length: 20}).map(Number.call, Number); return { dataSource: ds.cloneWithRows(data), }; }, render: function() { return ( <ListView contentContainerStyle={styles.list} dataSource={this.state.dataSource} renderRow={(rowData) => <Text style={styles.item}>{rowData}</Text>} /> ); } });
Just a ListView with some dummy data. Note the use of contentContainerStyle
. Here's the style object:
var styles = StyleSheet.create({ list: { flexDirection: 'row', flexWrap: 'wrap' }, item: { backgroundColor: 'red', margin: 3, width: 100 } });
We tell the container we want items in a wrapping row, and the we set the width of each child object.
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