Styled Components in 5 Minutes

Styled Components in 5 Minutes

Let's get right to it. CSS has become a bit of a weird "language" lately, with the rise of front-end frameworks. You can write it in CSS files and import it, or use CSS modules, or even inline-styling. You can even write CSS directly in javascript files.

Each option has it's pros and cons, but today we're looking at my personal favorite option, styled-components

What are Styled Components?

Styled components are exactly that: components for your Javascript app that are styled. Instead of seperating the logic by styling based on class names for your element, you're literally creating a custom HTML tag.

Pretty cool, huh?

Styled components make it easier to style each individual component, and you don't have to worry about CSS inheritance and the waterfall. No more !important!

Using styled-components

To get started using styled components, you need to install it.

npm install --save styled-components

After you install it, you can use it in any Javascript or Typescript file by importing it.

import styled from 'styled-components';

To create a styled component, you assign a variable to a new styled component (div, h1, or any valid HTML tag)

const CustomHeading = styled.h1`
  color: purple;
  background: white;
  font-size: 48px;
`;

To use this new styled component, you simply need to replace the <h1> tag with a <CustomHeading> tag.

From this:

<h1>My boring heading</h1>

To this!

<CustomHeading>My styled heading</CustomHeading>

Abra-cadabra. You just created a custom HTML tag (kind of, but same difference).

Why Should You Use Styled Components?

So, nice. Now you know what styled components are.

But why should you use them? Whats so great about them?

Well, I'm glad you asked!

Styled components have plenty of benefits, but a few of the most important ones are listed below.

No Classname Bugs or Conflicts

Whether you're an expert CSS developer or a beginner, you know this one fact, probably from experience: your component sometimes has styles that you have no clue where they came from.

Style components fixes this. Because your styles are directly tied to each component, or element, the styles for one element can't override another element's styles.

Automatic Critical CSS

One of my favorite things about styles components is the fact that it automtically uses critical CSS.

On page load, styled-components only loads the styles affecting the components on that page. So if you have a 100-page website, and you load the About page, the browser loads only the CSS that's used on the About page.

This means a faster website, and who doesn't want a fast website? 🚀

Dynamic Styling

Styled components also allow for dynamic styling, and in a lot simpler way the pure CSS.

For example, let's say we've got a menu that we want to show when the state is set to open, and hide when the state is closed.

Without styled-components, applying different styles requires writing two CSS classes: one for the open state and one for closed.

#menu {
  display: none;
  ...
}
#menu.open {
  display: block;
  ...
}

In order to use those different styles, we need to add/remove the classname from the menu using the DOM.

if (state.open) {
  document.getElementById('menu').classList.add('open');
} else {
  document.getElementById('menu').classList.remove('open');
}

Using styled components, however, we only need to pass in a prop to the component, just as we usually do in React/Vue.

  <StyledMenu open={state.open}>
    Menu Stuff
  </StyledMenu>

In our styled component declaration, we simply add a ternary operator to decide which style to show.

const StyledMenu = styled.div`
  display: ${props => props.open ? 'block' : 'none'};
`;

Theming with Styled Components

Finally, styled components allows for easy theming. In pure CSS, you would have to rely on CSS variables, which are not yet fully supported.

:root {
  --primary-color: tomato;
}
.h1 {
  color: var(--primary-color);
}

Using styled components, we get the same functionality, with better browser support and an easier-to-use syntax.

First, define a theme at the top-level of your site (i.e index.js).

const theme = {
  color: {
    primary: 'tomato',
  }
}

Then, wrap the component in a ThemeProvider, which is imported from styled-components.

import { ThemeProvider } from 'styled-components';
return (
  <ThemeProvider theme={theme}>
    ...
  </ThemeProvider>
);

Then, you can access the theme props from any styled component that's created in a component nested inside the root component.

const StyledButton = styled.button`
  background: ${props => props.theme.color.primary};
`;

Advanced Learning

So, I hope you've learned something new in this post! If you're interested in learning more about styled components, here are some resources:

Thanks for reading! If you liked this article, you can check me out on Twitter, or on my website!

p.s For those of you wondering, the official reading time for this article is 3 minutes and 41 seconds 😉⏳

Written by

Jarod Peachey

Jarod Peachey is a front end developer and JAMstack enthusiast. He's the founder of The Five Minute Developer, and https://staticbox.io. It would make him happy if you followed him on Twitter. And maybe check out his website.