Emotion: (emotion-theming) do i use withTheme or not?

Created on 21 Nov 2017  路  6Comments  路  Source: emotion-js/emotion

reading this article: it says we no longer need to use withTheme.
https://medium.com/@tkh44/emotion-8-9f892346d0af

image

But clicking into the documentation of emotion-theming, it says to use it...
https://github.com/emotion-js/emotion/blob/master/packages/emotion-theming/README.md#api

sooo, do I use it or not?

All 6 comments

or is that that i need to wrap components with withTheme, just not wrap styled.div``??

You don't need to use withTheme() on components created with react-emotion like:

const Thing = styled.div`
  color: {p => p.theme.color};
`;

However if you want to consume theme properties in a normal React component, that's when you use the withTheme() HOC.

class MyComponent extends React.Component {
  render() {
    return <div>{this.props.theme.text}</div>
  }
}

const ThemedMyComponent = withTheme(MyComponent);

The wording in the docs is a bit confusing still.

Image 2019-06-04 at 10 43 43 AM

Also, there are no examples of function components here. Is there a reason for that?

Also, there are no examples of function components here. Is there a reason for that?

No, there is not - it's just the same with class component as it is with function ones.

Thanks, @Andarist. Reason I ask is I was using with Flow, and it didn't pick up the Props. Can open a separate issue if you'd like.

Image 2019-06-04 at 2 53 57 PM

A separate implementation I have seen is something like this:

const _ThemeContext: React.Context<Theme> = React.createContext(defaultTheme);
_ThemeContext.displayName = 'ThemeContext';
const ThemeContext = Object.create(_ThemeContext);

export {ThemeContext};

export const useTheme = () => React.useContext(_ThemeContext);

export const withTheme = <Props: {theme: Theme}>(
  Component: React.AbstractComponent<Props>
): React.AbstractComponent<$Diff<Props, {theme: Theme}>> => {
  const NewComponent = React.memo(props => (
    <Component {...props} theme={useTheme()} />
  ));
  NewComponent.displayName = Component.displayName || Component.name || 'Component'
  return NewComponent;
};

Better to open a new issue then

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MrFungusEli picture MrFungusEli  路  3Comments

johnbrett picture johnbrett  路  3Comments

meebix picture meebix  路  3Comments

AlexanderProd picture AlexanderProd  路  3Comments

mattfysh picture mattfysh  路  3Comments