Logo

Programming

Styled Components Advanced Usage

Onur Demirtaş
Onur DemirtaşFebruary 22, 2020
WhatsappLinkedIn
Article Hero Image

Using Variables

It is possible to use javascript variables with styled components. All you need to do is to create a Javascript variable with template literal.

const myStyle = `
  width: 300px;
  height: 100px;
`

Then we can use this variable anywhere in the main style block:

export default styled.div`
  .container {
    ${myStyle}
  }
  .container2 {
    ${myStyle}
  }
`

Responsive Media Queries

It is possible to create some break points and use them with styled components. First of all create a file named 'devices.js' and add this content:

const mobile = "768px";
const tablet = "992px";
const desktop = "1200px";

export default {
  mobile: `@media (max-width: ${mobile})`,
  tablet: `@media (min-width: ${mobile}) and (max-width: ${tablet})`,
  desktop: `@media (min-width: ${tablet}) and (max-width: ${desktop})`,
  largeScreen: `@media (min-width: ${desktop})`
};

You can change the breakpoint values as you wish.

In style file import this module and use it anywhere you want to use the breakpoints:

import Devices from "devices";


export default styled.div`
  .title {
    ${Devices.mobile} {
      text-align: left;
    }
  }
`

Theme Provider

Styled Components has an helper Component called ThemeProvider for theming. It is using Context API behind the scenes:

import styled, { ThemeProvider } from 'styled-components';

const Wrapper = styled.div`
  color: ${props => props.theme.color};

render(
  <ThemeProvider theme={{ color: 'red' }}>
    <Wrapper>I'm red!</Wrapper>
  </ThemeProvider>
)

Global Styles

Styled Components has a helper function called 'createGlobalStyle' to define global styles in your app. Previously we were creating separate component using styled components and wrapping the whole application with that component. However with 'createGlobalStyle' we don't have to do that. According to Styled Components documentation:

"Normally, styled components are automatically scoped to a local CSS class and therefore isolated from other components. In the case of createGlobalStyle, this limitation is removed and things like CSS resets or base stylesheets can be applied."


Let's see an example:

import { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
  }

<>
  <GlobalStyle whiteColor />
  <App />
</>

It is also possible to use createGlobalStyle with ThemeProvider:

import { createGlobalStyle, ThemeProvider } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
    font-family: ${props => props.theme.fontFamily};
  }

<ThemeProvider theme={{ fontFamily: 'Helvetica Neue' }}>
  <>
    <GlobalStyle whiteColor />
    <App />
  </>
</ThemeProvider>