Great way of using styled components

February 22, 2021
views 2 min read

In the past I've used styled-components in pretty much all my pet projects. Truth be told is that after a while my components started to look really messy.

When you're dealing with small components is fine, but once you have multiple elements it's a mess.


Lets take the next example:

export default function App() {
  return (
    <>
      <h1>Hello!</h1>
      <p>
        Want to learn a neat way of using styled-components?
      </p>
    </>
  )
}

We'll convert both the h1 and p. First we need to install styled-components:

npm i styled-components

We should be ready to convert our elements:

import styled from 'styled-components';

const Title = styled.h1`
  font-family: "Helvetica";
`

const Paragraph = styled.p`
  font-family: "Helvetica";
  font-size: 18px;
  color: #666;
`

export default function App() {
  return (
    <>
      <Title>Hello!</Title>
      <Paragraph>
        Want to learn a neat way of using styled-components?
      </Paragraph>
    </>
  )
}

This is good, but can you image being 10 elements instead of 2? What a mess.


The way I used to approach this was by creating a styles.js file to hold my styles:

// styles.js
export const Title = styled.h1`
  font-family: "Helvetica";
`;

export const Paragraph = styled.p`
  font-family: "Helvetica";
  font-size: 18px;
  color: #666;
`;

// index.js
import { Title, Paragraph } from './styles'

Good stuff! But again, lets imagine we have 10+ elements, our import would look something like this:

import {
  Title,
  Paragraph,
  Header,
  Button,
  Secondary,
  Image,
  HeroCover,
  SideBar,
  // ... and so on!
} from './styles'

Don't like this approach at all! Solution? Import all!

import * as S from './styles'

I like to call is S because you know, Styles. You can name it whatever you want.

It's also easier to identify which components are styled:

<>
  <S.Title>Hello!</S.Title>
  <S.Paragraph>
    Want to learn a neat way of using styled-components?
  </S.Paragraph>
</>

Boom! Easy and really helpful ✌🏻

Read next
Junior vs Senior Developers
May 25, 2021
views