Let’s see how the above example could look with using higher order functions.

const MyBox = styled.div`

background-color: ${color('primary')};

color: ${color('primary', 'contrastText')};

padding: ${spacing(2)}

`;

Way easier to to read and scan, right?

Let’s implement the color function:

const color = (variant, type = 'main') =>

props => props.theme.palette[variant][type];

Additionally you could create shortcut functions like this:

const primaryColor = type => color('primary', type);

const secondaryColor = type => color('secondary', type);

const contrastTextColor = (variant) => color(variant, 'contrastText');

But you don’t need to stop there, you can even build something like a styled-system inside more complexly styled components. This is extremely handy when you want to combine more than 4 or 5 different styling parameters (that otherwise would make your JSX less readable when using styled-system).

const MyBox = styled.div`

${mx(2)};

${mt(1)};

${mb(3)};

${shadow(2)};

display: flex;

justify-content: space-between;

`;

The benefit of using something like this, is that you can combine more complex styling together with design system values like spacing, shadows or colours. Writing this in a system like styled-system or @material-ui/system adds a lot of noise in your actual JSX.

<Box mx={2} mt={1} mb={3} shadow={2} display="flex" justifyContent="space-between">

// ...

</Box>

Also it cuts down time writing common css property names hundreds of times.

The margin functions implemented in with the material-ui theme could something look like this:

Conclusion

Higher order functions give you many creative possibilities to write helper functions, that increase readability and scan-ability, reduce coding time, and combined with descriptive naming also help others understand your styled components better.

What is your experience on higher order functions in combination with styled-components? Do you have questions? Or do you have some more handy use cases for this? Share your thoughts with me, I’m interested!

P.S.: We are currently building a service for visual component review in GitHub Pull Requests. This way you can quickly show new and changed components to designers, so they can give feedback even before your Pull Request is merged. If you are interested, visit our website www.bojagi.io. You can add yourself to the beta waiting list and get early hands on.