1

Can anyone recommend the best way to compose styled-components that need to be themed?

Here's my code: https://gist.github.com/aaronmcadam/7bfd63a6bc4cfc36f9947a449c6f494a.

I have an Avatar component which composes an Image component, which is itself a styled-component.

If I use Avatar.styled.js with <ThemeProvider>, the theme can be successfully overridden.

If I use Avatar.withTheme.js, the theme can only be overridden if I use withTheme.

Which is the preferred way of doing things like these?

Aaron McAdam
  • 706
  • 2
  • 7
  • 20

1 Answers1

4

from the official docs: https://github.com/styled-components/styled-components/blob/master/docs/theming.md

We export a component that takes a theme prop. The theme you provide there is injected into your styled components via props.theme

If you ever need to get 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() {
    const { theme } = this.props

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

export default withTheme(MyComponent)
Community
  • 1
  • 1
Moe
  • 3,467
  • 1
  • 19
  • 25
  • Thanks Mohamed. I'm more looking for what the preferred style is for composing themed `styled-components` – Aaron McAdam Mar 29 '17 at 10:26
  • 1
    check this it might help, it explains why withTheme was created in the first place: http://stackoverflow.com/questions/40796973/how-to-get-the-theme-outside-styled-components – Moe Mar 29 '17 at 10:39
  • 1
    I don't think there is a "preferred style", it depends a lot on the context of your application and what you're trying to do. Either one is fine from our perspective! (styled-components co-creator here) – mxstbr Mar 30 '17 at 13:30