DEV Community

Cover image for How to use Styled Components with React.js
Pratham
Pratham

Posted on

How to use Styled Components with React.js

Styled Components is react library that allows us to style react components individually.

In this tutorial, you will learn about styled-components & how to use styled-components in your React application.

We can use styled-components in React & react-native applications but this guide will focus only on using styled-components with React.


Table of contents:

  • What are Styled-components ?
  • But why Styled-components ?
  • Installing styled-components
  • Getting started
  • Props in styled-components
  • Make it Responsive
  • Overriding Styles
  • Global styling
  • Conclusion

What are Styled-components ?

Styled Components allows us to write CSS in JavaScript

It is a component-based framework specially developed for react & react-native applications which uses component-based approach to manage our styles.

It removes the mapping between components and styles. This means that when you're defining your styles, you're actually creating a normal React component, that has your styles attached to it.


But why Styled-components ?

Reusable styles: You're writing CSS in a component-based approach which means once you define your styles you can use that anywhere inside your project.

No class name bugs: In styled-components you don't have to worry about naming conventions, the library provides unique class name that eliminates duplication, overlap or misspellings errors.

Easy to manage CSS: You never have to find different files affecting the styling which makes it easier to manage CSS.

Eliminates unused code: If any specific styled-component is unused it automatically deletes all its styles.


Installing styled-components

Start by creating react application

npx create-react-app styled-components-tutorial

To use styled-components, you first have to install it using npm or yarn.

    # with npm
    npm install --save styled-components

    # with yarn
    yarn add styled-components
Enter fullscreen mode Exit fullscreen mode

or if you're not using any package manager you can use styled-components with CDN, just add this to bottom of your html file.

    <script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Getting started

styled-components uses tagged template literals to style your components.

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

    // Creating a Heading styled-component that'll render an <h1> tag with some additional styles
    const Heading = styled.h1`
      font-size: 1.5em;
      color: #2F9ED8;
    `;

    // Creating a Container styled-component that'll render an <section> tag with some additional styles
    const Container = styled.section`
      padding: 4em;
      background: #B6585F;
    `;

    function App() {
      return (
        <div>
          <Container>
            <Heading>Styled Components</Heading>
          </Container>
        </div>
      );
    }
Enter fullscreen mode Exit fullscreen mode

You can visit codesandbox & see the output.

In the above example we created styled-components inside existing component file. we can also create a separate file for styled-components.

    // Heading.js
    import styled from 'styled-components';

    const Heading = styled.h1`
      font-size: 1.5em;
      color: #2F9ED8;
    `;

    export default Heading;
Enter fullscreen mode Exit fullscreen mode

Now you can use Heading Component in any component of the project.

    // App.js
    import React from 'react';
    import styled from 'styled-components';

    // import the styled component:
    import Heading from './Heading';

    const App = () => {
      return (
         <div>
            <Heading>Styled Components</Heading>
        </div>
      )
    }
    export default App;
Enter fullscreen mode Exit fullscreen mode

Props in styled components

Styled components are functional components which means we can style components dynamically.
To make our components styles dynamic we use props.

Let's take a look at example

Suppose you want different buttons in your application (for ex. Primary, Danger, etc)

    const Button = styled.button`
      background: ${props => props.primary ? "blue" : "white"};
      color: ${props => props.primary ? "white" : "blue"};

      font-size: 1em;
      margin: 1em;
      padding: 0.25em 1em;
      border: 2px solid blue;
      border-radius: 3px;
    `;

    return(
      <div>
        <Button>Normal</Button>
        <Button primary>Primary</Button>
      </div>
    );
Enter fullscreen mode Exit fullscreen mode

We are rendering two button components, one normal button & one with "primary" as prop.

Live code example here.


Make it Responsive

To make your components responsive we can use media-queries just as we use them in plain CSS.

    const Button = styled.button`
      background: ${props => props.primary ? "blue" : "white"};
      color: ${props => props.primary ? "white" : "blue"};

      font-size: 1em;
      margin: 1em;
      padding: 0.25em 1em;
      border: 2px solid blue;
      border-radius: 3px;

      @media (min-width: 768px) { 
        padding: 1rem 2rem;
        width: 11rem;
      }

      @media (min-width: 1024px) { 
        padding: 1.5rem 2.5rem;
        width: 13rem;
      }
    `;

    return(
      <div>
        <Button>Normal</Button>
        <Button primary>Primary</Button>
      </div>
    );
Enter fullscreen mode Exit fullscreen mode

Overriding styles

To change a component slightly we can extend the style for a single use case.

For example:

    const Button = styled.button`
      color: blue;
      font-size: 1em;
      margin: 1em;
      padding: 0.25em 1em;
      border: 2px solid palevioletred;
      border-radius: 3px;
    `;

    const TomatoButton = styled(Button)`
      color: tomato;
      border-color: tomato;
    `;

    return(
      <div>
        <Button>Normal Button</Button>
        <TomatoButton>Tomato Button</TomatoButton>
      </div>
    );
Enter fullscreen mode Exit fullscreen mode

Global Styling

Thankfully, we have a bult-in function createGlobalStyle in styled-components to apply global styles to our component.

We can use createGlobalStyle to set same font-family, override default-browser styling, etc. (you got the point.)

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

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

    const App = () => {
      return (
        <>
          <GlobalStyle />
          <Container>
            <Nav />
            <Content />
          </Container>
        </>
      )
    }
    export default App;
Enter fullscreen mode Exit fullscreen mode

Note: Styles created with createGlobalStyle do not accept any children

and that's it!

give yourself a pat on the back if you've made it till the end.


Conclusion

We covered the fundamentals & some basic concepts of styled-components & they are enough to get you rolling.

Now don't stop here use styled-components in your next project and see how it goes.

Don't forget to check out styled-components documentation.

Top comments (0)