Joel M. Turner

Illustration

Blog

Notes

My Favorite Layout Components in React

There are a few components that I use almost every day in development. They are used for layouts and are made from flexbox and css grid. On this site I pass both of these down with the MdxProvider so all my pages and posts have access to them easily.

Flexbox

This one is by far my favorite. 90% of the time it works perfectly with the props given. It can easily be extended through styled components, emotion’s css prop, or Theme UI’s sx prop for those few cases where I need something extra.

This is definitely an opinionated way to build a Flexbox component. The idea is to have booleans for certain aspects of the spec to help speed up composition.

Here’s a list of the current props for it:

1type FlexboxProps = {
2 className?: string;
3 children?: React.ReactNode;
4
5 inline?: boolean;
6 vertical?: boolean; // column
7 wrap?: boolean;
8 noGrow?: boolean; // acts as no-grow and no-shrink
9 grow?: number;
10 shrink?: number;
11 basis?: number | "auto";
12
13 top?: boolean;
14 middle?: boolean;
15 bottom?: boolean;
16 left?: boolean;
17 center?: boolean;
18 right?: boolean;
19 between?: boolean;
20 around?: boolean;
21 gap?: boolean | number; // add margin between children similar to grid-gap on grid
22}

Here is some example usage. See the CodeSandbox down below for more.

1<Flexbox vertical gap={3}>
2 <Flexbox noGrow>
3 <h1>A Title for You</h1>
4 </Flexbox>
5 <Flexbox bottom>
6 <p>This is some copy to show how the box will fill the whole area but the text will be aligned bottom.</p>
7 </Flexbox>
8</Flexbox>

Grid

Grid is another one of my favorites and it’s also very opinionated to suit my needs. The idea is to use CSS grid to create layouts. Depending on the project it can align with a design grid.

This can be paired with Flexbox for some powerful layouts. Add the sx prop from Theme UI for some wonderful breakpoint awesomeness.

Let’s take a look at the props.

1type GridProps = {
2 className?: string;
3 children: React.ReactNode;
4 gap?: string | number; // grid-gap
5 columns?: string | string[]; // grid-template-columns
6 rows?: string | string[]; // grid-template-rows
7}

Here’s an example of using it. See more examples in the CodeSandbox.

1<Grid columns="1fr 1fr" gap="2">
2 <img src="myImage.png" />
3 <img src='catsSinging.png' />
4</Grid>

Examples

I had used a column component that accepted different span amounts but I ended up not using it as much. I tend to add span to the children through the sx prop or extending with styled components.

Discuss this article on Twitter