Tuesday, 25 August, 2020 UTC


Summary

In this lesson we’ll create the fourth layout primitive component — Stack, that will allow us (together with the Box, Flex and Grid components from the previous lesson) to create almost any complex layout without writing any custom CSS. We’ll use [Styled System](https://styled-system.com/) to create this component. Stack component is a layout primitive to create stacking — adding equal spacing between each child of a container, and it’s one of the most useful layout primitives. Stack is based on the [Box](https://egghead.io/lessons/react-creating-the-box-layout-primitive-component-using-styled-system) component, and adds spacing between the container children. We can use it like this: ```jsx eins zwei polizei ``` This will create three `
`s stacked one on top of the other with a 8 pixels (third step in our spacing scale) gap. The implementation is based on the [lobotomized owl CSS selector](https://alistapart.com/article/axiomatic-css-and-lobotomized-owls/): ```css .stack * + * { margin-top: 8px; } ``` Here we’re adding a top margin to each container child except the first one, so we’re creating whitespace *between* the children but not around the container. To define the `gap` prop — the spacing between the container children — we'll use [the system function](https://styled-system.com/api#system) from styled-system, that allows us to create custom props. The Stack implementation in this lesson is slightly simplified one, [have a look at a more flexible Stack component](https://github.com/tamiadev/tamia/blob/master/src/components/Stack.tsx) that supports vertical and horizontal stacking, and switching direction based on the viewport width. **We’ll use following libraries:** * [styled-components](https://styled-components.com/) * [Styled System](https://styled-system.com/) You can either use this lesson’s [Git repository](https://github.com/sapegin/cddcourse) or install them manually in your project: ``` npm install styled-components styled-system ``` **Useful links and documentation:** * [Styled System docs](https://styled-system.com/getting-started/) * [Styled System system()](https://styled-system.com/api#system) * [Build a Box](https://styled-system.com/guides/build-a-box) * [Axiomatic CSS and Lobotomized Owls](https://alistapart.com/article/axiomatic-css-and-lobotomized-owls/) * [The Stack on Every Layout](https://every-layout.dev/layouts/stack/) * [More flexible Stack component implementation](https://github.com/tamiadev/tamia/blob/master/src/components/Stack.tsx)