Skip to content

Instantly share code, notes, and snippets.

@Zealur
Last active March 12, 2021 15:54
Show Gist options
  • Save Zealur/3de7b874d8dd3af5a96decb619b060f9 to your computer and use it in GitHub Desktop.
Save Zealur/3de7b874d8dd3af5a96decb619b060f9 to your computer and use it in GitHub Desktop.
Styled Components Conclusions

Story of styled components:

First: create seperate component for every DOM element that needs any styling

small margin needed => create separate component in separate file with unique name probably like this:

export const StyledSearchSelectListItemPreviewButtonIconWrapper = styled.div'
 margin-left: 0.8rem;
';

and then you have separate component for each element that need slight styling which ends up in having 100 components with margin-left: 0.8rem or margin-left: 1.2rem or margin-left: 0.7rem... with such funky names.


Hold on! Why not just create special component for this? like:

<Margin left="0.8rem"> ... </Margin>

Great idea!

I have created <Margin>! then <Display> ... then <Padding>... then <Border> and here is my beatifull result:

    <Display display="flex">
        <Margin margin="0 2.4rem">
            <Border border="1px solid black">
                <Padding padding="0.6rem">
                    Dupa
                </Padding>
            </Border>
        </Margin>
    </Display>

And output has also much more div's than needed so it's perfect, the more the better :) enter image description here


Man... just put some effort into it, create one COOL component that can handle all of this.

Alright! alright...

Here we go:

export const ContentContainer = styled.div<{
  display?: CSS.DisplayProperty;
  margin?: CSS.MarginProperty;
  maxWidth?: CSS.MaxWidthProperty;
  flex?: CSS.FlexProperty;
  padding?: CSS.PaddingProperty;
  ...
}>`
  display: ${({ display }) => display || 'block'};
  margin: ${({ margin }) => margin || '0 auto'};
  padding: ${({ padding }) => padding || '0'};
  max-width: ${({ maxWidth }) => maxWidth || '100%'};
  ${({ flex }) =>
    flex &&
    css`
      flex: ${flex};
    `}
  ...
`;

Great! I've rewritten whole CSS into this component, now we have everything!

  <ContentContainer display="flex" alignItems="center" justifyContent="center" margin="0.4rem"...>
    Dupa
  </ContentContainer>

🎉 TADA! And we are back 20 years into inline-styling! Good job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment