Modulo to the Rescue

Posted by Isabel Vazquez on May 12, 2019
[ react  bootstrap  design  ]

Earlier this year, I ran into an issue where I mapped the backend response (panels) into one column but received feedback that the UI was having odd spacing when one panel was closed. Below are simplified bits of the code that I worked with to give an idea on how to approach this code issue.

Problematic UI Code

renderChildren = () => {
    const children = (fields, model, modelIndex) => {
        return fields.map((field) => {
           return <Col sm={6}>
                <FormGroup>
                    <ControlLabel>{field.label}</ControlLabel>
                    <InputGroup>
                        <FormControl
                            name={field.label}
                            value={field.value}
                        />
                    </InputGroup>
                </FormGroup>
           </Col>
        })
    }

    return this.state.models.map((node, index) => {
        return <Col sm={6}>
                <Panel defaultOpen title={node.model}>
                    { children(node.fields, node.model, index) }
                </Panel>
        </Col>
    })
}

<Col className="info" sm={12}>
    {this.renderChildren()} 
</Col>

In the code above, I was imitating two columns by placing col-sm-6 columns into one col-sm-12 column. However, in order to have clearer spacing, I needed to actually implement two columns:

Solution Part 1

<Col sm={12} className="info">
    <Col sm={6}>
        {this.renderChildren(leftElements)}
    </Col>
    <Col sm={6}>
        {this.renderChildren(rightElements)}
    </Col>
</Col>

So rather than mapping this.state.models, renderChildren() would map either of the following parameters: leftElements or rightElements. this.state.models is still where the backend response was captured. I ended up using the state with a modulo to create the new parameters.

Solution Part 2

const rightElements = [];
const leftElements= [];
_.forEach(this.state.models, (model, index) =>
    index % 2 === 0 && index !== 0 ?
        rightElements.push(model) :
        leftElements.push(model)
);