Back to Styled Components

Theme Consumer

sections/api/helpers/theme-consumer.mdx

latest1.0 KB
Original Source

ThemeConsumer | v4

Prefer useTheme hook: For function components, the useTheme hook provides a simpler API. ThemeConsumer is primarily useful for class components.

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.

tsx
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>
    )
  }
}

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.