I am creating a grid with ListView. This is my code
export default class CategoryContainer2 extends Component {
constructor() {
super();
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(['row 1', 'row 2','row 3','row 4','row 5']),
};
}
render() {
return (
<View style={{
backgroundColor:'#ebeef0',
alignItems:'center',
justifyContent:'center'}}>
<ListView contentContainerStyle={styles.list}
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text style={styles.item}>{rowData}</Text>}
/>
</View>
);
}
}
and this is the result
As you can see in my code, I am trying to center the grid in the screen, but this is not working. Do you have an idea on how to do that?
EDIT:
If there is only one line on the grid than the view is centered
If I increase the size of the items and the grid contains more than one line, center dose not work anymore
EDIT:
Here is s snack with the problem.
One of the easiest ways of centering the content of grid items is using Flexbox. Set the display to "grid" for the grid container, and "flex" for grid items. Then, add the align-items and justify-content properties, both with the "center" value, to grid items.
I believe problem is caused by ListView
width being same as the container View
width. I have 2 ideas on how to achieve desired behavior.
For both idea I added paddingLeft
and paddingRight
to container View
to center ListView
.
First idea is that setting ListView
style justifyContent: 'space-between'
or justifyContent: 'space-around'
. This option allows to have different size of items in a row and every row will contain the most amount of item it can fit. But this option makes the second row items have different margins between items when the row is not full.
Second idea is to calculate width
of the items and then setting up a fixed amount of items in each row. This option is more controlled but requires to fix width of the items.
I'm adding a screen of 2 different approach and here is the sample app's snack
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