This post is written primarily for the students in my React Application Workshop, but may be useful for anyone who wants to build layouts in Chakra UI.
Flex
Our first layout component we will look at is the Flex
component. The Flex
component is essentially a Box
with display: flex;
. You can use it to make horizontal and vertical layouts. The advantage of this component is that it has these shorthands for Flexbox properties:
flexDirection
isdirection
flexWrap
iswrap
flexBasis
isbasis
flexGrow
isgrow
flexShrink
isshrink
alignItems
isalign
justifyContent
isjustify
Experiment in the sandbox below (be sure to read and understand the code):
Spacer
The Spacer
component is designed to be used alongside Flex
. It creates a space as large as possible between two components. You can use it to create navbars like the one below. Notice how the Spacer
is in between the two components where the space goes. This time, we are using a Flex
with direction="column"
Practical Usage
Most apps can be made almost entirely using Flex
es for layout. The most common layout in app design, is a vertical or horizontal layout. Most of the time, these layouts are nested. In a simple todo app, we would usually have a top level horizontal layout with both the sidebar and the main area, inside the sidebar a list of items (a vertical layout), and another vetical layout in the main area holding all the todos. Each todo itself is a horizontal layout.
Note that in the demo below, the checkboxes will not work as the done
state is hardcoded. To get that to work, we need to modify the state whenever the checkbox changes.