Atomic CSS using styled-components
Disclaimer: I'm no expert on Atomic CSS. I have just learned this pattern and excited to share my knowledge. If you want to deep dive in this topic please refer links in the resources section
In this post. I will try to make to introduce you with a CSS design pattern which is currently gaining popularity in the frontend community.
Also, I will be showing you how you can achieve this with styled-component in your react app.
What is Atomic CSS?
The definition according to css-tricks is
Atomic CSS is the approach to CSS architecture that favors small, single-purpose classes with names based on visual function.
According to me, it's a functional way of writing CSS. Writing smallest possible utility and then composing it to achieve bigger components.
Mixins in Style-components
In order to compose styles in styled-components, we will be using mixin.
Let's look into a small example of a mixin.
const padding = props => (props.padding ? `padding: ${props.padding}px;` : "padding: 0px;");
const Box = styled.div`
${padding}
background-color: red;
`;
then you can use this in your react components like this
<Box padding={20}>Box</Box>
Now using mixins to achieve Atomic CSS
const padding = props =>
({ padding } ? `padding: ${props.padding}px;` : "padding: 0px;");
const bgr_blue = `background-color: #357edd;`
const br_20 = `border-radius: 20px;`
const Box = styled.div`
${padding}
${bgr_blue}
${br_20}
`;
Full Working Example
You can find full working codesandbox example here
Resources:
Top comments (0)