Create the Box Layout Primitive Component Using Styled System

InstructorArtem Sapegin

Share this video with your friends

Send Tweet

In this lesson we’ll create the base layout primitive component — Box, that will allow us (together with other layout primitives) to create almost any complex layout without writing custom CSS. We’ll use Styled System to create this component.

Styled System allows us to create React components, where we can control styles using component props.

Fox example, a simplified Box component:

import styled from 'styled-components';
import { space, color, layout } from 'styled-system';

export const Box = styled.div(space, color, layout);

By default, it renders a <div> element without any styles, and we can control typography, spacing and color using props.

Here we’re defining width, padding, bottom margin, and background color:

<Box width={[1, 1 / 2]} p={4} mb={3} bg="primary">
  I’m a primary box, with responsive width, some padding, and bottom margin

Each of these props can accept an array to make it responsive: we can pass up to three value for mobile, tablet and desktop breakpoints. For example, above we have a smaller width on wide screens. Also, all these values will be taken from the site theme, which makes our UI consistent. In the example above, it will take the value of the primary color from the theme for the background color, and the fifth item in the spacing scale for padding.

Prop names are camel cased CSS property names, with a few shortcuts like p, px, py for padding, m, mx, my for margins, and bg for background color.

We’ll use following libraries:

You can either use this lesson’s Git repository or install them manually in your project:

npm install styled-components styled-system @styled-system/prop-types

Useful links and documentation: