DEV Community

Germán Llorente
Germán Llorente

Posted on • Updated on

Simple layouts with Flexbox in React

Every time I have to do an UI, the most tedious task I face is align elements inside a div, either vertically or horizontally.

However, since I got to know Flexbox, all this has changed, aligning elements became a very easy task.

If you don't know about Flexbox, I suggest you read this guide, it's very clear: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

I work with React, so, nothing is easier than having a couple of components (Row and Column) that can be used as follow:

import { Column, Row } from 'simple-flexbox';
...
<Column flexGrow={1}>
    <Row horizontal='center'>
        <h1>HEADER</h1>
    </Row>
    <Row vertical='center'>
        <Column flexGrow={1} horizontal='center'>
            <h3> Column 1 </h3>
            <span> column 1 content </span>
        </Column>
        <Column flexGrow={1} horizontal='center'>
            <h3> Column 2 </h3>
            <span> column 2 content </span>
        </Column>
    </Row>
</Column>
Enter fullscreen mode Exit fullscreen mode

And get the next result:
result

See a live example here: https://codesandbox.io/s/rwyl6zyp0p?module=%2FExample.js

A header, two columns, all the content is centered, and no CSS lines. I've tried to keep it as simple as possible.
However, you have access to all the advanced features of Flexbox, and you can even send your own styles to Row and Column, ie:

<Row
    flexGrow={1}
    flexBasis='auto'
    horizontal='space-between'
    style={{ backgroundColor: 'blue' }}
>
Enter fullscreen mode Exit fullscreen mode

This module named simple-flexbox is published in npm, and you can see its code and documentation here:
https://github.com/llorentegerman/simple-flexbox

In the following link there are several advanced examples, which I will update periodically:
https://codesandbox.io/s/z3p04l3vol

I hope you find them useful

Top comments (2)

Collapse
 
smit1999 profile image
Smit Shah

The link for learning flex box was really helpful. Thanks a ton!

Collapse
 
llorentegerman profile image
Germán Llorente

Thanks to you! Glad you found this useful