Style Your React App Using Styled-Components

Styled-components is a library for React & React Native to write and manage your CSS.

·

5 min read

From the beginning of Web1.0 to Web3.0, Web technologies have been through multiple advancements. From Static to Dynamic websites, jQuery to today’s React, Next.js, Angular, or Vue.js — JavaScript libraries and frameworks. If you observe the advancement in styling methodologies for websites or web applications in recent years, we now have multiple ways of writing CSS (Cascading Style Sheet). We have seen and used some of the feature-rich CSS like SAAS, LESS, BEM, etc. We have options to select from the list of CSS methodologies we want to include in our application.

If you are looking for CSS architecture that is modular just like React and keeps your codebase clean, styled components will help you solve this.

Prerequisites

A basic understanding of React or React-Native development is recommended before working on Styled Components.

Styled Components Overview

styled-components is a library for React & React Native to write and manage your CSS. They allow you to write CSS in your JavaScript(CSS-in-JS), keeping your CSS in very close proximity to your JavaScript for a single component.

styled-components allows you to write actual CSS code to style your components. It also removes the mapping between components and styles.

Getting started with styled-component

First, we need to install styled-components into our React project.

npm install styled-components

On every component that you use styled-components, you’ll need to add this import.

import styled from 'styled-components';

You can check the styled-components library details here.

Creating a styled component

After installing the styled-components dependency, let's create our first styled component. We will create a form component with one input field to accept emails and a button for submitting the entered email.

For the input field and button, we will create styled-components called StyledInput and StyledButton respectively.

import React, {useEffect} from "react";
// importing styled from styled component
import styled from "styled-components";

//Button component - which render <button> with mentioned styles
const StyledButton = styled.button`
  background-colour: blue;
  color: white;
  padding: 1rem 2rem;
`
// Input field component - which renders <input /> with mentioned styles
const StyledInput = styled.input`
  width: 400px;
  height: 34px;
  outline: none;
`

const FormContainer = () => {
  const [inputValue, setInputValue] = useState('');

  const onClick = () => {
    // onclick functionality code
  }
  return(
    <>
      <StyledInput
         type="email"
         value={inputValue}
         placeholder="Enter Email"
         onChange={e => setInputValue(e.target.value)}
      />
      <StyledButton onClick={() => {onClick}}>
         {btnText}
      </StyledButton>
    </>
  )
};

export default FormContainer;

In the above snippet, We use the internal utility method styled, which transforms the styling from JavaScript into actual CSS. Followed by the HTML element we want to style - styled.button and then add backticks to denote our template into which we add regular CSS syntax.

const StyledButton = styled.button`
   background-colour: blue;
   color: white;
   padding: 1rem 2rem;
`

Similarly, for StyledInput, we use styled.input continued with the CSS code.

const StyledInput = styled.input`
    width: 400px;
    height: 34px;
    outline: none;
`

The and returned inside the FromContainer component look like a normal React component. And that’s because it is a React component!

Handling pseudo-selectors and media query

Adding media queries for responsive styled-component is simple. Just write media queries inside your template literal as shown below.

...
const StyledButton = styled.button`
   background-colour: blue;
   color: white;
   padding: 1rem 2rem;
   @media (min-width: 768px) {
      padding: 2rem 4rem;
      width: 11rem;
   }
   @media (min-width: 1024px) {
      padding: 4rem 8rem;
      width: 13rem;
   }
`
...

Similar to adding media queries to your Styled Components, adding pseudo-selectors are pretty straightforward. For example:

...
const StyledButton = styled.button`
   background-colour: blue;
   color: white;
   padding: 1rem 2rem;
   :hover {
     border-color: green;
   }
`
...

Using React props in styled-components

So, when you create a styled component, what you’re actually creating is a React component with styles. In our previous example, StyledButton is the styled component, and it will be rendered as an HTML button with the contained styles.

If styled-components are React components, Then we can also use props in styled-components. Since the styled-components are functional, we can style elements dynamically.

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

const Block = styled.div`
  width: 400px;
  height: 400px;
  background-color: ${props => props.color || "blue"};
`;

const BlockContainer = () => {
  return(
    <>
      <Block color='red'>Item 1</Block>
      <Block color='green'>Item 2</Block>
    </>
  );
}

export default BlockContainer;

As you can see in the code above, We have created only one styled-component Block and using color props we will change the background. This helps in modifying your CSS conditionally with props.

We use a callback function provided by styled-components to conditionally change the style.

Global Styling

Now, If you want to override global styling — for example, You want to change the background and font of the body element. You can use createGlobalStyle to achieve this. It’s recommended to use createGlobalStyle in top-level Components or in general App.js, which are shared over multiple pages rather than using it on a single page.

import React from 'react';
import styled, { createGlobalStyle } from 'styled-components';
import { Container } from '../components';

const GlobalStyle = createGlobalStyle`
  body {
    margin: 0;
    padding: 0;
    background: teal;
    font-family: Open-Sans, Helvetica, Sans-Serif;
  }
`;

const App = () => {
  return (
    <>
      <GlobalStyle />
      <Container>
        ...
      </Container>
    </>
  )
}
export default App;

Advanatges & Conclusion

Styled components have multiple advantages over conventional CSS methodologies. Some of them will be — Easy-to-understand syntax. All the unused CSS and styling get removed automatically, even if they’re declared in your code.

You don’t write any class names, they are generated automatically, so there’s no need to manage the CSS class naming methodology.

With CSS-in-JS, CSS selectors are scoped automatically to their components. This makes it much easier to know how to edit a component’s CSS as there’s never any confusion about how and where CSS is being used.