Create the Box Layout Primitive Component Using Styled System

Artem Sapegin
InstructorArtem Sapegin

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

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:

Artem Sapegin: [0:00] Let's create a new markdown file and add some usage examples. Ceate a JavaScript file and start styleguidist to see what we're doing. Import styled-components. Import all the functions from styled-system we're going to use.

[0:15] Each styled-system function defines a certain number of props. For example, spacing, colors, borders, layout, flexbox properties, or use of grid properties. Create a new styled-component, define border boxSizing for convenience, and paste all style system functions to the styled-components factory.

[0:36] Export our component. Let's also define some propTypes. That system exports propTypes for all its functions. We can change all the styles with props now. For example, make the padding larger, change the background color, and so on.