Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a grid inside a view

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

enter image description here

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

enter image description here

If I increase the size of the items and the grid contains more than one line, center dose not work anymore

enter image description here

EDIT:

Here is s snack with the problem.

like image 680
user567 Avatar asked Oct 24 '17 07:10

user567


People also ask

How do I center my grid on the screen?

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.


1 Answers

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

screen of 2 options

like image 59
bennygenel Avatar answered Nov 15 '22 03:11

bennygenel