API Reference

Primary

styled

This is the default export. This is a low-level factory we use to create the styled.tagname helper methods.

ArgumentsDescription
1. component / tagnameEither a valid react component or a tagname like 'div'.

Returns a function that accepts a tagged template literal and turns it into a StyledComponent.

// import styled from 'styled-components'

const Button = styled.button`
  background: palevioletred;
  border-radius: 3px;
  border: none;
  color: white;
`

const TomatoButton = styled(Button)`
  background: tomato;
`

render(
  <>
    <Button>I'm purple.</Button>
    <br />
    <TomatoButton>I'm red.</TomatoButton>
  </>
)

You can see this method being introduced in the Getting started section.

TaggedTemplateLiteral

This is what you pass into your styled calls – a tagged template literal. This is an ES6 language feature. You can learn more about them in the Tagged Template Literals section.

InputsDescription
RuleAny CSS rules (string)
InterpolationThis can either be a string or a function. Strings are combined with the rules as-is. Functions will receive the styled component's props as the first and only argument.

Read more about how to adapt styling based on props in the Adapting based on props section.

The properties that are passed into an interpolated function get attached a special property, theme, which is injected by a higher level ThemeProvider component. Check the section on Theming for more information on this.

// import styled from 'styled-components'

const padding = '3em'

const Section = styled.section`
  color: white;

  /* Pass variables as inputs */
  padding: ${padding};

  /* Adjust the background from the properties */
  background: ${props => props.background};
`

render(
  <Section background="cornflowerblue">
    ✨ Magic
  </Section>
)
✨ Magic

You can also return objects from interpolations or input objects directly, and they'll be treated as inline styles. However this is highly discouraged, as the CSS syntax has support for pseudo selectors, media queries, nesting, etc., which the object syntax doesn't.

StyledComponent

A styled React component. This is returned when you call styled.tagname or styled(Component) with styles.

This component can take any prop. It passes it on to the HTML node if it's a valid attribute, otherwise it only passes it into interpolated functions. (see Tagged Template Literal)

You can pass an arbitrary classname to a styled component without problem and it will be applied next to the styles defined by the styled call. (e.g. <MyStyledComp className="bootstrap__btn" />)

.attrs

This is a chainable method that attaches some props to a styled component. The first and only argument is an object that will be merged into the rest of the component's props. The attrs object accepts the following values:

ValuesDescription
Prop ValueThese can be of any type, except functions. They'll stay static and will be merged into the existing component props.
Prop FactoryA function that receives the props that are passed into the component and computes a value, that is then going to be merged into the existing component props.

Returns another StyledComponent.

// import styled from 'styled-components'

const Input = styled.input.attrs({
  type: 'text',
  size: props => (props.small ? 5 : undefined),
})`
  border-radius: 3px;
  border: 1px solid palevioletred;
  display: block;
  margin: 0 0 1em;
  padding: ${props => props.padding};

  ::placeholder {
    color: palevioletred;
  }
`

render(
  <>
    <Input small placeholder="Small" />
    <Input placeholder="Normal" />
    <Input padding="2em" placeholder="Padded" />
  </>
)

Learn more about this constructor in the Attaching Additional Props section.

.withComponent

This is a method that creates a new StyledComponent with a different tag or component applied to it, but all the same rules of the one it's called on.

ArgumentsDescription
1. component / tagnameEither a valid react component or a tagname like `'div'`.

Returns a new StyledComponent with the new tag / component being applied when it's used.

You can see it in action in the Extending Styles section.

Note

As of styled-components v4 the withComponent API is now a candidate for deprecation. In all likelihood, you probably want to use the new "as" prop to simply switch what element/component being rendered since the withComponent API is destructive toward styles if the lowest-wrapped component is a StyledComponent.

"as" polymorphic prop
v4

If you want to keep all the styling you've applied to a component but just switch out what's being ultimately rendered (be it a different HTML tag or a different custom component), you can use the "as" prop to do this at runtime.

// import styled from "styled-components";

const Component = styled.div`
  color: red;
`;

render(
  <Component
    as="button"
    onClick={() => alert('It works!')}
  >
    Hello World!
  </Component>
)

This sort of thing is very useful in use cases like a navigation bar where some of the items should be links and some just buttons, but all be styled the same way.

ThemeProvider

A helper component for theming. Injects the theme into all styled components anywhere beneath it in the component tree, via the context API. Check the section on Theming.

PropsDescription
themeAn object that will be injected as theme into all interpolations in styled components beneath the provider.
// import styled, { ThemeProvider } from 'styled-components'

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

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

Helpers

createGlobalStyle
v4

A helper function to generate a special StyledComponent that handles global styles. 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.

ArgumentsDescription
1. TaggedTemplateLiteralA tagged template literal with your CSS and interpolations.

Returns a StyledComponent that does not accept children. Place it at the top of your React tree and the global styles will be injected when the component is "rendered".

import { createGlobalStyle } from 'styled-components'

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

// later in your app

<React.Fragment>
  <Navigation /> {/* example of other top-level stuff */}
  <GlobalStyle whiteColor />
</React.Fragment>

Since the GlobalStyle component is a StyledComponent, that means it also has access to theming from the <ThemeProvider> component if provided.

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

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

// later in your app

<ThemeProvider theme={{ fontFamily: 'Helvetica Neue' }}>
  <React.Fragment>
    <Navigation /> {/* example of other top-level stuff */}
    <GlobalStyle whiteColor />
  </React.Fragment>
</ThemeProvider>

css

A helper function to generate CSS from a template literal with interpolations. You need to use this if you return a template literal with interpolations inside an interpolation. (This is due to how tagged template literals work)

If you're just returning a normal string you do not need to use this.

ArgumentsDescription
1. TaggedTemplateLiteralA tagged template literal with your CSS and interpolations.

Returns an array of interpolations, which is a flattened data structure that you can pass as an interpolation itself.

import styled, { css } from 'styled-components'

const complexMixin = css`
  color: ${props => (props.whiteColor ? 'white' : 'black')};
`

const StyledComp = styled.div`
  /* This is an example of a nested interpolation */
  ${props => (props.complex ? complexMixin : 'color: blue;')};
`

If you leave off the css your function will be toString()ed and you'll not get the results you expected.

keyframes
web-only

A helper method to create keyframes for animations.

ArgumentsDescription
1. TaggedTemplateLiteralA tagged template literal with your keyframes inside.

Returns a Keyframes model, to be used in your animation declarations. You can use the getName() API on the returned model if you wish to obtain the generated animation name.

Note

In styled-components v3 and below, the keyframes helper directly returned the animation name instead of an object with the getName method.

import styled, { keyframes } from 'styled-components'

const fadeIn = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
`

const FadeInButton = styled.button`
  animation: 1s ${fadeIn} ease-out;
`

If you are composing your style rule as a partial, make sure to use the css helper.

import styled, { css, keyframes } from 'styled-components'

const pulse = keyframes`
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
`

const animation = props =>
  css`
    ${pulse} ${props.animationLength} infinite alternate;
  `

const PulseButton = styled.button`
  animation: ${animation};
`

You can learn more about styled-components with Animations in the Animations

isStyledComponent

A utility to help identify styled components.

ArgumentsDescription
1. FunctionAny function expected to possibly be a styled component or React component wrapped in a styled component

Returns true if the passed function is a valid styled components-wrapped component class. It can be useful for determining if a component needs to be wrapped such that it can be used as a component selector:

import React from 'react'
import styled, { isStyledComponent } from 'styled-components'
import MaybeStyledComponent from './somewhere-else'

let TargetedComponent = isStyledComponent(MaybeStyledComponent)
  ? MaybeStyledComponent
  : styled(MaybeStyledComponent)``

const ParentComponent = styled.div`
  color: cornflowerblue;

  ${TargetedComponent} {
    color: tomato;
  }
`

withTheme

This is a higher order component factory to get the current theme from a ThemeProvider and pass it to your component as a theme prop.

ArgumentsDescription
1. ComponentAny valid React component that can handle a theme prop.

Returns the passed component inside a wrapper (higher order component). The passed component will receive a theme prop with the current theme object.

import { withTheme } from 'styled-components'

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

export default withTheme(MyComponent)
Note

All styled components automatically receive the theme as a prop, so this is only necessary if you wish to access the theme for other reasons.

ThemeConsumer
v4

This is the "consumer" component created by React.createContext as the companion component to ThemeProvider. It uses the render prop pattern to allow for dynamic access to the theme during rendering.

It passes the current theme (based on a ThemeProvider higher in your component tree) as an argument to the child function. From this function, you may return further JSX or nothing.

import { ThemeConsumer } from 'styled-components'

export default class MyComponent extends React.Component {
  render() {
    return (
      <ThemeConsumer>
        {theme => <div>The theme color is {theme.color}.</div>}
      </ThemeConsumer>
    )
  }
}
Note

All styled components automatically receive the theme as a prop, so this is only necessary if you wish to access the theme for other reasons.

Test Utilities

find
v3

A convenience method to find a single instance of a styled component's rendered DOM node within a given DOM root.

import styled, { find } from 'styled-components/test-utils'

const Foo = styled.div`
  color: red;
`

/**
 * Somewhere in your app:
 *
 * ReactDOM.render(
 *   <main>
 *     <Foo />
 *   </main>, document.body
 * );
 */

// retrieves the first instance of "Foo" in the body (querySelector under the hood)
find(document.body, Foo) // HTMLDivElement | null

findAll
v3

A convenience method to find all instances of a styled component's rendered DOM node within a given DOM root.

import styled, { findAll } from 'styled-components/test-utils'

const Foo = styled.div`
  color: ${p => p.color};
`

/**
 * Somewhere in your app:
 *
 * ReactDOM.render(
 *   <main>
 *     <Foo color="red" />
 *     <Foo color="green" />
 *   </main>, document.body
 * );
 */

// retrieves a NodeList of instances of "Foo" in the body (querySelectorAll under the hood)
findAll(document.body, Foo) // NodeList<HTMLDivElement> | null

enzymeFind
v4

A convenience method for finding instances of a particular styled component within an enyzme wrapper.

import { mount } from 'enzyme'
import styled, { enzymeFind } from 'styled-components/test-utils'

const Foo = styled.div`
  color: red;
`

const wrapper = mount(
  <div>
    <Foo>bar</Foo>
  </div>
)

enzymeFind(wrapper, Foo)

Supported CSS

Within a styled component, we support all of CSS plus nesting. Since we generate an actual stylesheet and not inline styles, whatever works in CSS works in styled-components!

const Example = styled.div`
  /* all declarations will be prefixed */
  padding: 2em 1em;
  background: papayawhip;

  /* pseudo selectors work as well */
  &:hover {
    background: palevioletred;
  }

  /* media queries are no problem */
  @media (max-width: 600px) {
    background: tomato;

    /* nested rules work as expected */
    &:hover {
      background: yellow;
    }
  }

  > p {
    /* descendant-selectors work as well, but are more of an escape hatch */
    text-decoration: underline;
  }

  /* Contextual selectors work as well */
  html.test & {
    display: none;
  }
`;

render(
  <Example>
    <p>Hello World!</p>
  </Example>
);

Hello World!

Ampersands (&) get replaced by our generated, unique classname for that styled component, making it easy to have complex logic.

Flow

styled-components has first-class Flow support to help you find typing errors while using our public API.

To use Flow with the public api of styled-components we recommend that you use the library definition in flow-typed. To install it you can use the flow-typed cli or download it manually from the git repository and store it in a flow-typed/ folder in the same directory with your flowconfig.

Installing the definitions

npm i -g flow-typed # if you do not already have flow-typed
flow-typed install styled-[email protected]<version>
Note

If you are on npm >= 5.2 you could simply use npx

Ignore styled-components source

You should add the following lines to your .flowconfig, if you run into Flow errors, coming from the styled-components package in your node_modules directory.

[ignore]
.*/node_modules/styled-components/.*

TypeScript

styled-components has TypeScript definitions to allow the library to be used in any TypeScript project. To install them, run:

npm install @types/styled-components

A basic example of usage can be found here.

Note

Now that Babel 7 is out and the TypeScript preset is available, it's now possible to use the styled-components babel plugin in conjunction with TypeScript.

Before you can effectively start to use TypeScript you will have to do a little bit of configuration.

Define a theme interface

By default every styled component will have the theme prop set to any. When building complex apps it would be better to have autocomplete and error checks everywhere.

To have autocomplete and checks around the theme prop we should first define the theme interface we would like to use throughout our app:

// theme.ts
export default interface ThemeInterface {
  primaryColor: string;
  primaryColorInverted: string;
}

Then we can re-export the styled function with our custom theme interface:

// styled-components.ts
import * as styledComponents from "styled-components";
import { ThemedStyledComponentsModule } from "styled-components";

import ThemeInterface from "./theme";

const {
  default: styled,
  css,
  injectGlobal,
  keyframes,
  ThemeProvider
} = styledComponents as ThemedStyledComponentsModule<ThemeInterface>;

export { css, injectGlobal, keyframes, ThemeProvider };
export default styled;

Styling components

Finally, instead of importing the styled functions from the styled-components module, we import it from our above, custom module.

import styled from 'app/styled-components';

// theme is now fully typed
const Title = styled.h1`
  color: ${props => props.theme.primaryColor};
`;

If you are passing custom properties to your styled component it is a good idea to follow this convention:

import styled from "app/styled-components"

// theme is now fully typed
const Title = styled<{ isActive: boolean }, "h1">("h1")`
  color: ${props => props.isActive ? props.theme.primaryColor : props.theme.secondaryColor}
`

You will need to define both the custom props and the type of tag which will be used. When you pass a custom component, the type of tag is not required.

import styled from 'app/styled-components';
import Header from './Header';

const Title =
  styled <{ isActive: boolean }>Header`
  color: ${props => (props.isActive ? props.theme.primaryColor : props.theme.secondaryColor)}
`;

If the isActive property should not be passed into the Header component you will have to extract it using the following convention:

import styled from 'app/styled-components';
import Header, { Props as HeaderProps } from './Header';

const Title =
  styled<{ isActive: boolean }>(({ isActive, ...rest }) => <Header {...rest} />)`
  color: ${props => (props.isActive ? props.theme.primaryColor : props.theme.secondaryColor)}
`;

But it might be the opposite. Maybe your styled component needs to proxy props required by the Header. Then you follow this convention:

import styled from 'app/styled-components';
import Header, { Props as HeaderProps } from './Header';

const Title =
  styled <{ isActive: boolean } & HeaderProps>(({ isActive, ...rest }) => <Header {...rest} />)`
  color: ${props => (props.isActive ? props.theme.primaryColor : props.theme.secondaryColor)}
`

This is the most complex example where we have specific properties for the styling of the component and pass the rest of the required properties by the Header through. That means when you use Title it will have the combined typing of both the styled requirements and the actual component requirements.

Caveat with className

When defining a component you will need to mark className as optional in your Props interface:

interface LogoProps {
  /* This prop is optional, since TypeScript won't know that it's passed by the wrapper */
  className?: string;
}

class Logo extends React.Component<LogoProps, {}> {
  render() {
    return <div className={this.props.className}>Logo</div>;
  }
}

const LogoStyled = styled(Logo)`
  font-family: 'Helvetica';
  font-weight: bold;
  font-size: 1.8rem;
`;

Caveat with Stateless Components

To use stateless components and have typechecking for the props you'll need to define the component alongside with its type. This is not special to styled-components, this is just how React works:

interface BoxProps {
  theme?: ThemeInterface;
  borders?: boolean;
  className?: string;
}

const Box: React.SFC<BoxProps> = props => <div className={props.className}>{props.children}</div>;

const StyledBox = styled(Box)`
  padding: ${props => props.theme.lateralPadding};
`;

Previous APIs

[Deprecated] .extend

Note

The .extend API was removed in styled-components v4. Use styled(StyledComponent) instead. For more information, see: https://github.com/styled-components/styled-components/issues/1546

This is a method that creates a new StyledComponent and extends its rules.

ArgumentsDescription
1. TaggedTemplateLiteralA tagged template literal with your CSS and interpolations.
import styled from 'styled-components'

const Component = styled.div`
  color: red;
`

const Component2 = Component.extend`
  background: white;
  color: blue;
`

Returns a new StyledComponent with the new rules merged into the ones of the component this method was called on.

[Deprecated] injectGlobal

Note

The injectGlobal API was removed and replaced by createGlobalStyle in styled-components v4.

A helper method to write global CSS. It does not return a component, but adds the styles to the stylesheet directly.

ArgumentsDescription
1. TaggedTemplateLiteralA tagged template literal with your global styles inside.
import { injectGlobal } from 'styled-components'

injectGlobal`
  @font-face {
    font-family: "Operator Mono";
    src: url("../fonts/Operator-Mono.ttf");
  }

  body {
    margin: 0;
  }
`

We do not encourage the use of this. Try to use it once per app at most, if you must, contained in a single file. This is an escape hatch. Only use it for the rare @font-face definition or body styling.

[Deprecated] "innerRef" prop

Note

The "innerRef" prop was removed in styled-components v4 in favor of the React 16 forwardRef API. Just use the normal ref prop instead.

Passing a ref prop to a styled component will give you an instance of the StyledComponent wrapper, but not to the underlying DOM node. This is due to how refs work. It's not possible to call DOM methods, like focus, on our wrappers directly.

To get a ref to the actual, wrapped DOM node, pass the callback to the innerRef prop instead.

Note

We don't support string refs (i.e. innerRef="node"), since they're already deprecated in React.

This example uses innerRef to save a ref to the styled input and focuses it once the user hovers over it.

const Input = styled.input`
  padding: 0.5em;
  margin: 0.5em;
  color: palevioletred;
  background: papayawhip;
  border: none;
  border-radius: 3px;
`

class Form extends React.Component {
  render() {
    return (
      <Input
        placeholder="Hover here..."
        innerRef={x => {
          this.input = x
        }}
        onMouseEnter={() => this.input.focus()}
      />
    )
  }
}

Continue on the next page

Tooling