This video is available to students only

The Stack Component

The Stack layout pattern is one of the most simple and common layout patterns on the web. In this lesson, you will learn how to build the Stack primitive and how to make it configurable for your situation

One of the simplest and yet most common layout patterns found on the web is putting one element on top of another element with consistent space. From form labels, to paragraphs of text, to social media feeds. They all need to stack one thing on top of another with uniform space between them. This problem is precisely what the Stack primitive solves.

The problem: Subscribe to Our Newsletter#

In this lesson, we are going to build the following widget:

Subscribe to Our Newsletter mockup

As you will notice, we have a few parts to this widget. There is a title section and a form section made up of two input groups and a button. The one thing that they all have in common is that they follow the same pattern. They all stack vertically with space between them. Here is the same mockup with the different space sizes pointed out.

Subscribe to Our Newsletter mockup with redlines

What we need is a way to enforce that all the items will stack in the block direction no matter if they are block or inline elements by default. We also need a way to provide consistent space between the elements without creating space around the stacked elements themselves. That way the stack can remain composable into any other environments.

The solution#

We are going to be doing the rest of the lessons in If you want to follow along, Here is a starter project you can fork or you can click on the final code at the end the lesson.

Let's start off with some basic markup. Create a new file with the extension .jsx.

(You can call it what you like. In this lesson, I am choosing to structure my files in a way that should make it easier to focus on what is being taught and not necessarily the way I would structure it for a production app. Although React doesn't have an opinion on how to structure your files, I typically like to collocate my components together as much as possible, and will separate files when components are reused across other parts of the application.)

And this is what that looks like:

initial layout

The first problem we want to solve is to get the label to stack on top of our input. This problem is easily solved with a single line of CSS:

We create a new Stack component and set the display property to grid, thereby implicitly setting a single column track for items inside the Stack. Each item that is placed in that column creates an implicit row. We can then use this new Stack component like this:

Our widget has already taken a major step in the right direction:


This page is a preview of Composing Layouts in React

Start a new discussion. All notification go to the author.