Make Styling Your React Apps Fun By Using Styled Components

Written by Igor DumencicPublished on July 27, 2019Filed under ReactJS
Styled Components Logo

Hi! This is my first blog post so I’ll try to make it a good one. I don’t write very often so I guess this will be quite a challenge for me. Today’s topic will be Styled Components, they’re already well known but I still wanted to write this post, so let’s get right into it.

What Are Styled Components?

Styled Components are CSS-in-JS framework, they offer you the ability to style your applications using CSS and advantages offered by ES6!

Here is a quick explanation from the official docs:

Utilising tagged template literals (a recent addition to JavaScript) and the power of CSS, styled-components allows you to write actual CSS code to style your components. It also removes the mapping between components and styles – using components as a low-level styling construct could not be easier!

Simple example of a Styled Component:

import React from 'react'
import styled from 'styled-components'

// Create a Title component that will render and <h1> tag
const Title = styled.h1`
 font-size: 3rem;
`

// Use Title like any other React component!
const App = () => (
  <Title>Styled Components are awesome!😎</Title>
)

As you can see, the whole idea is to make components just like the ones you’re making when using React. You create a Styled Component by calling styled function and specifying an HTML tag you want to create. Here is a list of all available tags.

styled.h1 is just a shortcut for styled('h1'), this is an ES6 featured called tagged templates. 🙂


Advantages Of Using Styled Components

Scoped Styles

Because CSS is global by nature it can get frustrating when you change a style of a particular element or class in your stylesheet and it unexpectedly changes a random element or behavior in the DOM. So using Styled Components will drastically help you because they’re component-based and very scoped.

Goodbye Class Name Bugs

Every Styled Component will have its unique class name that gets automatically generated so you will never have to worry about duplication, overlap or misspellings!

Enjoyable Dynamic Styling

You can adapt the style of your component based on its props or a global theme.

import React from 'react'
import styled from 'styled-components'

const Title = styled.h1`
 font-size: 3rem;
`

// Component that will change color based on the passed props
const Subtitle = styled.h2`
  font-size: 1.5rem;
  color: ${props => props.color ? 'black'}
`

const App = () => (
  <Title>Styled components are awesome!😎</Title>
  // This Subtitle will be black
  <Subtitle>Without props</Subtitle>
  // This Subtitle will be red
  <Subtitle color={'red'}>With props</Subtitle>
)

export default App

Reusability

Styled Components allows us to make reusable components with ease as they directly contain their style values which remove the need for mapping between components and their respective CSS.

Better Performance

Styled Components keeps track of which components are rendered on the screen and only injects their styles and nothing else that makes them very efficient and makes sure to load the less amount of code that’s necessary.

Automatic Vendor Prefixing

It can get tough to make your website look the same on all browsers, vendor prefixes are used to support the latest CSS features, but with Styled Components, you don’t have to worry about this anymore.

Easy Maintenance

Because every style is component-based finding the styling that is affecting your component is not a problem no matter how big your project is.

Server Side Rendering Support

SSR is getting more popular because of all the benefits that it brings to the table and with the tools like Next, Gatsby or Nuxt it’s simple to set it up.

Styled Components team made sure to support this feature with stylesheet rehydration. The idea behind it is that every time you render your application on the server, you create a ServerStyleSheet. Example with Next.


Setup And Example

Open up codesandbox and select the create-react-app starter that you probably used many times before. Add the styled-components dependency and you’re all set. (For this example you’ll only need to understand some basics of Flexbox)

We will create a very simple layout displaying the navbar component and some cards that will represent our posts.

The end result can be found here.

1. Navbar Component

Make a new file Navbar.js under /src/components/ directory, make sure to import both React from react and styled from styled-components.

// Navbar.js

import React from "react";
import styled from "styled-components";

// Wrapper component that wraps both logo and menu
const Wrapper = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #2276ff;
  padding: 15px;
`;

// Simple Logo component
const Logo = styled.h1`
  font-size: 2.5rem;
  color: white;
`;

// Link component with :hover style!
const Link = styled.a`
  color: white;
  cursor: pointer;
  margin-left: 10px;
  text-decoration: none;

  :hover {
    color: #ccc;
  }
`;

const Navbar = () => {
  return (
    <Wrapper>
      <Logo>TechNews</Logo>
      <menu>
        <Link href="#">Home</Link>
        <Link href="#">Contact</Link>
      </menu>
    </Wrapper>
  );
};

export default Navbar;

2. PostList Component

Now that we’ve made the navbar it’s time to create PostList component that will contain our posts.

// PostList.js

import React from "react";
import styled from "styled-components";

// Dummy data that we will map through
import posts from "../posts";
// We haven't made this component yet but we will in the next step
import Post from "./Post";

// Flex container that will contain all our posts
const Container = styled.div`
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
`;

const PostList = () => {
  return (
    <Container>
      // Add the code below AFTER next step
      {posts.map(({ id, name, description }) => (
        <Post key={id} name={name} description={description} />
      ))}
    </Container>
  );
};

export default PostList;

PostList will .map through a list of data ( you can use a .json file containing an array of blog posts for example) and render each post.

3. Post Component

Post component will receive props in the form of its title and description.

// Post.js

import React from "react";
import styled from "styled-components";

// Wrapper for our posts
const Card = styled.div`
  background-color: #ccc;
  padding: 30px;
  margin: 10px;
  text-align: center;
`;

const PostTitle = styled.h2`
  margin-bottom: 10px;
`;

const PostDescription = styled.p`
  font-style: italic;
  margin-bottom: 10px;
`;

const PostLink = styled.a`
  color: #2276ff;
  cursor: pointer;
  text-decoration: none;

  :hover {
    text-decoration: underline;
  }
`;

const Post = ({ name, description }) => {
  return (
    <Card>
      <PostTitle>{name}</PostTitle>
      <PostDescription>{description}</PostDescription>
      <PostLink href="#">Read More</PostLink>
    </Card>
  );
};

export default Post;

You can now go back to step 2 to add the required code, after that you should see the final result of this mini-project. 🎉

*GOING ONE STEP FURTHER WITH DYNAMIC STYLING

Inside of our Navbar.js file we will use props to conditionally set the opacity of our links.

// Navbar.js

import React from "react";
import styled from "styled-components";

// Wrapper component that wraps both logo and menu
const Wrapper = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #2276ff;
  padding: 15px;
`;

// Simple Logo component
const Logo = styled.h1`
  font-size: 2.5rem;
  color: white;
`;

// We will set the correct opacity based on the props we pass to the component
const Link = styled.a`
  color: white;
  opacity: ${props => (props.active ? 1 : 0.5)};
  cursor: pointer;
  margin-left: 10px;
  text-decoration: none;

  :hover {
    color: #ccc;
  }
`;

const Navbar = () => {
  return (
    <Wrapper>
      <Logo>TechNews</Logo>
      <menu>
        // Will have opacity set to 1
        <Link href="#" active>
          Home
        </Link>
        // Will have opacity set to 0.5
        <Link href="#">Contact</Link>
      </menu>
    </Wrapper>
  );
};

export default Navbar;

With this very simple example you can see how easy it is to dynamically change styles just by passing props to our component.
I would encourage you to play around with this mini-project to practice what you’ve learned. (You can add a Footer component for example)

Wrapping Up

I’ve been enjoying styling my apps using Styled Components, they’re so much fun to work with and offer you many benefits that will increase your productivity and speed up your workflow.

If you’d like to learn more advanced features of Styled Components make sure to check the official docs. 👍

Now I’m going a bit off-topic with this but I would just like to say that I’m not a native-English speaker. There are probably some grammar mistakes but I will do my best to improve my writing skills.

Thank you for making it this far and I’ll see you next Wednesday! 🙂

TAGS:

CSSHTMLJavaScriptReactJSStyled Components

Join the Newsletter

Subscribe to get my latest content
by email.



I won't send you spam, unsubscribe at any time.