DEV Community

Cover image for My 3 Different Ways To Write Styled Components
Jerm
Jerm

Posted on

My 3 Different Ways To Write Styled Components

Hi there

Hello, this is my first blog/article post, I'll be posting a lot on my journey to build websites/app worthy of being on Awwwards, what I learn along the way, and just anything that I find interesting and want to share. Feedback is always appreciated, so feel free to grill me on my grammar :P

Different ways to write styled-components

These are just a few different ways that I've come across when using Styled Components in my React projects. Let me know what you like best and or any other ways that you have found and enjoyed using. (I'm currently using style three)

Style One - Standard

// Component/styles.js
const FlexWrapper = styled.div`
  ...
`

const Item = styled.span`
  display: flex;
  align-items: center;
`;

const ButtonPadding = styled.div`
    padding: 0 1rem;
`

export { FlexWrapper , Item, ButtonPadding  };

// Component/index.js

import { FlexWrapper, Item } from './styles.js' // how I import and then use the styled components

A Styled Component is created for any element that needs styling. I used this style when I first started with React and Styled Components.

Style Two

//Component/styles.js
const Wrapper= styled.div`
  display: flex;
  font-size: 14px;
  margin-top: 36px;
  align-items: center;

  .button {
     padding: 0 1rem;
  }

  a {
    text-decoration: none;
    cursor: pointer;
  }

  .breadcrumb-icon {
    margin: 0 8px;
  }

  .icon-inner {
    // ...
  }
`;

//Component/index.js

// ...
return <>
    <Wrapper>
         <a>Item 1 <img className="breadcrumb-icon"/></a>
         // ...
    </Wrapper>
</>

We defined one wrapper/container component that encompasses the component you are building, and just target the html elements from there. This saves us from having to create a Styled Component for every element that needs styling.

Style Three

// Tabs/styleds.js
// ...
export { Tabs, RightSide, Bar };

// Tabs/index.js
import * as S from './styles';
// ...
return (
      <S.Tabs>
        <S.Bar>
          <TabStrip onSelect={onSelect} tabs={mappedTabs} />
          <S.RightSide>
            <S.RightSide>{rightSide}</S.RightSide>
          </S.RightSide>
        </S.Bar>
        {selectedTab && selectedTab.props.children}
      </S.Tabs>
    );

One thing I like about this approach is that it's very easy to determine to React components and Styled Components apart, it also saves you from having to import every new Styled Component each time you create one. I found this when looking at this open source project https://github.com/kitze/JSUI

I'd be interested to hear what everyone else is using, so let me know :)

Top comments (0)