When writing a project in React, there are many ways to style our react components.

  1. Define styles in CSS files.
  2. Define styles using preprocessors like SASS.
  3. Use inline styles.
  4. Use css-in-js

Styled-components come under 'css-in-js'. It basically is a way to conveniently manage our styles by writing them inside the Javascript file itself. As the official styled-components documentation says, styled-components is the result of wondering how we could enhance CSS for styling React component systems.

styled-components
Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅🏾

First of all we need to install the library using npm or yarn

npm i --save styled-components 
yarn add styled-components

Then we need to import it inside the required file.

import styled from 'styled-components';

The syntax for styled-components is something like the following.

const MyDiv = styled.div`
    border: 1px solid red;
    fontSize: 16px;
`

return (
    <MyDiv>Hello there</MyDiv>
)

You can see how 'MyDiv' styles are defined inside the backticks in the above code block. This method is required when writing styles. We have defined the MyDiv to be a div element with the mentioned border and the font-size. Also notice the camel-case used for the attribute names inside the style definition.

This play a very important role in simplifying the way how we write styles for react components. It makes the components easily reusable and scalable.

Why styled-components?

There are many reasons why developers tend to use styled-components over traditional styling methods.

  1. Automatic critical CSS - Keeping track of which components are being rendered on screen and injects only those styles.
  2. No class name bugs - As unique class names are generated for the components, no duplication, overlap or misspellings.
  3. Easier deletion of CSS - No need to stress upon garbage css as when a component is deleted, the styles can also get deleted along.
  4. Simple dynamic styling - Styles can be matched based on a global theme or passed props.
  5. Painless maintenance - No need to hunt across different files to find the styling affecting a particular component as all the styles are in itself.
  6. Automatic vendor prefixing - Styled-components add the vendor prefixes, we only need to write standard CSS.

Using SCSS Features/Syntax with styled-components

We can also write styles using scss along with styled-components.

1) Media queries

const MyDiv = styled.div`
    border: 1px solid red;
    fontSize: 16px;
    @media (max-width: 1000px) {
      background-color: red;
    }
`

2) Nesting styles

const MyDiv = styled.div`
    border: 1px solid red;
    fontSize: 16px;
    img {
      width: 120px;
      height: 100px;
    }
`

3) Pseudo classes

const MyDiv = styled.div`
    border: 1px solid red;
    fontSize: 16px;
    &:hover {
      background: yellow
    }
`

4) Pseudo elements

const MyDiv = styled.div`
    border: 1px solid red;
    fontSize: 16px;
    &:after {
      content: '';
      border: 1px solid blue;
    }
`

Conditional Styling with props

We can define props in the styled-component and render the styles conditionally. This allows us to have dynamic styling inside our application.

const Label = styled.div`
  background: #000;
  color: ${(props) => (props.primary ? "#fff" : "#ccc")};
`;

return (
    <Label primary>First name</Label>
)

Using Global Themes

We can globally define themes and use them in application styles. For that we need to import ThemeProvider from styled components.

import React from "react";
import { ThemeProvider } from "styled-components";

Then we have to define a theme object which will be accepted by the ThemeProvider.

const theme = {
  colors: {
    myred: "FF5733",
    mygreen: "#20CE3F"
  },
}

Then we have to provide the theme to the ThemeProvider and export it

const Theme = ({ children }) => (
  <ThemeProvider theme={theme}>{children}</ThemeProvider>
);

export default Theme

Then we have to wrap the components we need within <Theme> tags and use the theme attributes in style definitions as below.

const Heading = styled.h1`
  color: ${({ theme: { colors } }) => colors.mygreen};
`;

const App = () => {
  return (
    <Theme>
      <Container>
        <Heading>Hello World</Heading>
        <h2>By the power of styled-components!</h2>
      </Container>
    </Theme>
  );
};

References