Search code examples
reactjssemantic-ui-react

Semantic UI react grid columns order


I have an ordered list of check boxes (this.state.columns):

1. 2. 3. 4. 5. 6. ...

and I want to display this list in two columns, but semantic ui grid it is changing the order to:

'1.' '2.'

'3.' '4.'

'5.' '6.'

This is my code:

<Grid stackable columns={2}>
        {this.state.columns.map(
          data =>
            data.label !== ' ' && (
              <Grid.Column key={data.key}>
                <Field
                  name={data.key}
                  component={fields.field.checkbox}
                  label={data.label}
                  type="checkbox"
                  control={Checkbox}
                />
              </Grid.Column>
            )
        )}
</Grid>

Any ideas on how to fix this? I need to be displayed like this:

'1.' '4.'

'2.' '5.'

'3.' '6.'


Solution

  • A Grid can have a Grid.Row and this should have a Grid.Column.

    You have defined your grid to have 2 columns; this should have your Component tree for the first 3 levels look similar to this:

    Grid
    ----Grid.Row
    ---------Grid.Column (GridColumn#1)
    ---------Grid.Column (GridColumn#2)

    GridColumn#1 will contain have of the data contained in this.state.columns and GridColumn#2 will contain the other half.

    You can get the half for GridColumn#1 by slicing the array up to half its length and from half its length for GridColumn#2.

    Note that you need to adjust this for cases where the array length for this.state.columns is odd. (in the example below, I have relied on the Javascript to convert floating point numbers to integer)

    Here is one way to implement this; it could benefit from some refactoring.

      renderCheckboxColumns() {
        const { columns } = this.state
        const leftColumns = columns.slice(0, (columns.length + 1 )/ 2).map(
          data =>
            <Grid.Row>
              <Grid.Column>{data}</Grid.Column>
            </Grid.Row>
        )
    
        const rightColumns = columns.slice((columns.length + 1)/ 2).map(
          data =>
            <Grid.Row>
              <Grid.Column>{data}</Grid.Column>
            </Grid.Row>
        )
    
        return (
          <Grid.Row>
            <Grid.Column>
              {leftColumns}
            </Grid.Column>
            <Grid.Column>
              {rightColumns}
            </Grid.Column>
          </Grid.Row>
        );
      }
    
      render() {
        return (
          <Grid stackable columns={2}>
            {this.renderCheckboxColumns()}
          </Grid>
    
        );
      }