Advanced Usage

Theming

styled-components has full theming support by exporting a <ThemeProvider> wrapper component. This component provides a theme to all React components underneath itself via the context API. In the render tree all styled-components will have access to the provided theme, even when they are multiple levels deep.

To illustrate this, let's create our Button component, but this time we'll pass some variables down as a theme.

Function themes

You can also pass a function for the theme prop. This function will receive the parent theme, that is from another <ThemeProvider> higher up the tree. This way themes themselves can be made contextual.

This example renders our above themed Button and a second one that uses a second ThemeProvider to invert the background and foreground colors. The function invertTheme receives the upper theme and creates a new one.

Getting the theme without styled components

via withTheme higher-order component

If you ever need to use the current theme outside styled components (e.g. inside big components), you can use the withTheme higher order component.

import { withTheme } from 'styled-components'


class MyComponent extends React.Component {
  render() {
    console.log('Current theme: ', this.props.theme)
    // ...
  }
}


export default withTheme(MyComponent)

via useContext React hook
v4

You can also use useContext to access the current theme outside of styled components when working with React Hooks.

import { useContext } from 'react'
import { ThemeContext } from 'styled-components'


const MyComponent = () => {
  const themeContext = useContext(ThemeContext)


  console.log('Current theme: ', themeContext)
  // ...
}

via useTheme custom hook
v5

You can also use useTheme to access the current theme outside of styled components when working with React Hooks.

import { useTheme } from 'styled-components'


const MyComponent = () => {
  const theme = useTheme()


  console.log('Current theme: ', theme)
  // ...
}

The theme prop

A theme can also be passed down to a component using the theme prop.

This is useful to circumvent a missing ThemeProvider or to override it.

Refs
v4

Passing a ref prop to a styled component will give you one of two things depending on the styled target:

  • the underlying DOM node (if targeting a basic element, e.g. styled.div)
  • a React component instance (if targeting a custom component e.g. extended from React.Component)
Note

Using an older version of styled-components (below 4.0.0) or of React? Use the innerRef prop instead.

Security

Since styled-components allows you to use arbitrary input as interpolations, you must be careful to sanitize that input. Using user input as styles can lead to any CSS being evaluated in the user's browser that an attacker can place in your application.

This example shows how bad user input can even lead to API endpoints being called on a user's behalf.

// Oh no! The user has given us a bad URL!
const userInput = '/api/withdraw-funds'


const ArbitraryComponent = styled.div`
  background: url(${userInput});
  /* More styles here... */
`

Be very careful! This is obviously a made-up example, but CSS injection can be unobvious and have bad repercussions. Some IE versions even execute arbitrary JavaScript within url declarations.

There is an upcoming standard to sanitize CSS from JavaScript, CSS.escape. It's not very well supported across browsers yet, so we recommend using the polyfill by Mathias Bynens in your app.

Existing CSS

There are a couple of implementation details that you should be aware of, if you choose to use styled-components together with existing CSS.

styled-components generates an actual stylesheet with classes, and attaches those classes to the DOM nodes of styled components via the className prop. It injects the generated stylesheet at the end of the head of the document during runtime.

Styling normal React components

If you use the styled(MyComponent) notation and MyComponent does not render the passed-in className prop, then no styles will be applied. To avoid this issue, make sure your component attaches the passed-in className to a DOM node:

class MyComponent extends React.Component {
  render() {
    // Attach the passed-in className to the DOM node
    return <div className={this.props.className} />
  }
}

If you have pre-existing styles with a class, you can combine the global class with the passed-in one:

class MyComponent extends React.Component {
  render() {
    // Attach the passed-in className to the DOM node
    return <div className={`some-global-class ${this.props.className}`} />
  }
}

Issues with specificity

If you apply a global class together with a styled component class, the result might not be what you're expecting. If a property is defined in both classes with the same specificity, the last one will win.

// MyComponent.js
const MyComponent = styled.div`background-color: green;`;


// my-component.css
.red-bg {
  background-color: red;
}


// For some reason this component still has a green background,
// even though you're trying to override it with the "red-bg" class!
<MyComponent className="red-bg" />

In the above example the styled component class takes precedence over the global class, since styled-components injects its styles during runtime at the end of the <head> by default. Thus its styles win over other single classname selectors.

One solution is to bump up the specificity of the selectors in your stylesheet:

/* my-component.css */
.red-bg.red-bg {
  background-color: red;
}

Avoiding conflicts with third-party styles and scripts

If you deploy styled-components on a page you don't fully control, you may need to take precautions to ensure that your component styles don't conflict with those of the host page.

The most common problem is insufficient specificity. For example, consider a host page with this style rule:

body.my-body button {
  padding: 24px;
}

Since the rule contains a classname and two tag names, it has higher specificity than the single classname selector generated by this styled component:

styled.button`
  padding: 16px;
`

There's no way to give your components complete immunity from the host page's styles, but you can at least boost the specificity of their style rules with babel-plugin-styled-components-css-namespace, which allows you to specify a CSS namespace for all of your styled components. A good namespace would be something like #my-widget, if all of your styled-components render in a container with id="my-widget", since ID selectors have more specificity than any number of classnames.

A rarer problem is conflicts between two instances of styled-components on the page. You can avoid this by defining process.env.SC_ATTR in the code bundle with your styled-components instance. This value overrides the default <style> tag attribute, data-styled (data-styled-components in v3 and lower), allowing each styled-components instance to recognize its own tags.

Tagged Template Literals

Tagged Template Literals are a new feature in ES6. They let you define custom string interpolation rules, which is how we're able to create styled components.

If you pass no interpolations, the first argument your function receives is an array with a string in it.

// These are equivalent:
fn`some string here`;
fn(['some string here']);

Once you pass interpolations, the array contains the passed string, split at the positions of the interpolations. The rest of the arguments will be the interpolations, in order.

const aVar = 'good';


// These are equivalent:
fn`this is a ${aVar} day`;
fn(['this is a ', ' day'], aVar);

This is a bit cumbersome to work with, but it means that we can receive variables, functions, or mixins (css helper) in styled components and can flatten that into pure CSS.

Speaking of which, during flattening, styled-components ignores interpolations that evaluate to undefined, null, false, or an empty string (""), which means you're free to use short-circuit evaluation to conditionally add CSS rules.

const Title = styled.h1<{ $upsideDown?: boolean; }>`
  /* Text centering won't break if props.$upsideDown is falsy */
  ${props => props.$upsideDown && 'transform: rotate(180deg);'}
  text-align: center;
`;

If you want to learn more about tagged template literals, check out Max Stoiber's article: The magic behind 💅🏾 styled-components

Server Side Rendering
v2+

styled-components supports concurrent server side rendering, with stylesheet rehydration. The basic idea is that everytime you render your app on the server, you can create a ServerStyleSheet and add a provider to your React tree, that accepts styles via a context API.

This doesn't interfere with global styles, such as keyframes or createGlobalStyle and allows you to use styled-components with React DOM's various SSR APIs.

Tooling setup

In order to reliably perform server side rendering and have the client side bundle pick up without issues, you'll need to use our babel plugin. It prevents checksum mismatches by adding a deterministic ID to each styled component. Refer to the tooling documentation for more information.

For TypeScript users, our resident TS guru Igor Oleinikov put together a TypeScript plugin for the webpack ts-loader / awesome-typescript-loader toolchain that accomplishes some similar tasks.

If possible, we definitely recommend using the babel plugin though because it is updated the most frequently. It's now possible to compile TypeScript using Babel, so it may be worth switching off TS loader and onto a pure Babel implementation to reap the ecosystem benefits.

Example

The basic API goes as follows:

import { renderToString } from 'react-dom/server';
import { ServerStyleSheet } from 'styled-components';


const sheet = new ServerStyleSheet();
try {
  const html = renderToString(sheet.collectStyles(<YourApp />));
  const styleTags = sheet.getStyleTags(); // or sheet.getStyleElement();
} catch (error) {
  // handle error
  console.error(error);
} finally {
  sheet.seal();
}

The collectStyles method wraps your element in a provider. Optionally you can use the StyleSheetManager provider directly, instead of this method. Just make sure not to use it on the client-side.

import { renderToString } from 'react-dom/server';
import { ServerStyleSheet, StyleSheetManager } from 'styled-components';


const sheet = new ServerStyleSheet();
try {
  const html = renderToString(
    <StyleSheetManager sheet={sheet.instance}>
      <YourApp />
    </StyleSheetManager>
  );
  const styleTags = sheet.getStyleTags(); // or sheet.getStyleElement();
} catch (error) {
  // handle error
  console.error(error);
} finally {
  sheet.seal();
}

The sheet.getStyleTags() returns a string of multiple <style> tags. You need to take this into account when adding the CSS string to your HTML output.

Alternatively the ServerStyleSheet instance also has a getStyleElement() method that returns an array of React elements.

If rendering fails for any reason it's a good idea to use try...catch...finally to ensure that the sheet object will always be available for garbage collection. Make sure sheet.seal() is only called after sheet.getStyleTags() or sheet.getStyleElement() have been called otherwise a different error will be thrown.

Note

sheet.getStyleTags() and sheet.getStyleElement() can only be called after your element is rendered. As a result, components from sheet.getStyleElement() cannot be combined with <YourApp /> into a larger component.

Next.js

With Babel

Basically you need to add a custom pages/_document.js (if you don't have one). Then copy the logic for styled-components to inject the server side rendered styles into the <head>.

Refer to our example in the Next.js repo for an up-to-date usage example.

With SWC

Since version 12, Next.js uses a Rust compiler called SWC. If you're not using any babel plugin, you should refer to this example instead.

On this version, you only need to add styledComponents: true, at the compiler options in the next.config.js file and modify _document file with getInitialProps as in this example to support SSR.

Gatsby

Gatsby has an official plugin that enables server-side rendering for styled-components.

Refer to the plugin's page for setup and usage instructions.

Streaming Rendering

styled-components offers a streaming API for use with ReactDOMServer.renderToNodeStream(). There are two parts to a streaming implementation:

On the server:

ReactDOMServer.renderToNodeStream emits a "readable" stream that styled-components wraps. As whole chunks of HTML are pushed onto the stream, if any corresponding styles are ready to be rendered, a style block is prepended to React's HTML and forwarded on to the client browser.

import { renderToNodeStream } from 'react-dom/server';
import styled, { ServerStyleSheet } from 'styled-components';


// if you're using express.js, you'd have access to the response object "res"


// typically you'd want to write some preliminary HTML, since React doesn't handle this
res.write('<html><head><title>Test</title></head><body>');


const Heading = styled.h1`
  color: red;
`;


const sheet = new ServerStyleSheet();
const jsx = sheet.collectStyles(<Heading>Hello SSR!</Heading>);
const stream = sheet.interleaveWithNodeStream(renderToNodeStream(jsx));


// you'd then pipe the stream into the response object until it's done
stream.pipe(res, { end: false });


// and finalize the response with closing HTML
stream.on('end', () => res.end('</body></html>'));

On the client:

import { hydrate } from 'react-dom';


hydrate();
// your client-side react implementation

After client-side rehydration is complete, styled-components will take over as usual and inject any further dynamic styles after the relocated streaming ones.

Referring to other components

Note

This is a web-specific API and you won't be able to use it in react-native.

There are many ways to apply contextual overrides to a component's styling. That being said, it rarely is easy without rigging up a well-known targeting CSS selector paradigm and then making them accessible for use in interpolations.

styled-components solves this use case cleanly via the "component selector" pattern. Whenever a component is created or wrapped by the styled() factory function, it is also assigned a stable CSS class for use in targeting. This allows for extremely powerful composition patterns without having to fuss around with naming and avoiding selector collisions.

A practical example: here, our Icon component defines its response to the parent Link being hovered:

We could have nested the color-changing rule within our Link component, but then we'd have to consider both sets of rules to understand why Icon behaves as it does.

Caveat

This behaviour is only supported within the context of Styled Components: attempting to mount B in the following example will fail because component A is an instance of React.Component not a Styled Component.

class A extends React.Component {
  render() {
    return <div />
  }
}


const B = styled.div`
  ${A} {
  }
`

The error thrown - Cannot call a class as a function - occurs because the styled component is attempting to call the component as an interpolation function.

However, wrapping A in a styled() factory makes it eligible for interpolation -- just make sure the wrapped component passes along className.

class A extends React.Component {
  render() {
    return <div className={this.props.className} />
  }
}


const StyledA = styled(A)``


const B = styled.div`
  ${StyledA} {
  }
`

Style Objects

styled-components optionally supports writing CSS as JavaScript objects instead of strings. This is particularly useful when you have existing style objects and want to gradually move to styled-components.

Continue on the next page

API Reference