Skip to content

Ability to create a class name string from a style object. #846

Open
@trustin

Description

Is your feature request related to a problem? Please describe.

I need to work with other components that don't work well with Styled System. They allow me to style them by specifying one or more class names, though.

For example, I need to specify two class names to style <CookieConsent /> (https://github.com/Mastermindzh/react-cookie-consent):

<CookieConsent
  declineButtonText="Opt out"
  buttonClasses="..."
  declineButtonClasses="..."
  ...
/>

Emotion provides a component called <ClassNames /> so a user can generate a cached class name from a style object, but it doesn't understand Styled System's theme object.

Describe the solution you'd like

To solve this issue, I wrote an alternative component which applies css() to a style object before passing the style object to Emotion's ClassNames:

import { ClassNames as EmotionClassNames, Interpolation } from '@emotion/core';
// @ts-ignore
import { useThemeUI } from '@theme-ui/core';
// @ts-ignore
import { css as themeUICss } from '@theme-ui/css';
import React from 'react';

interface ClassNamesContent {
  cssToClassName(styleObject: Interpolation): string;
}

interface ClassNamesProp {
  children(content: ClassNamesContent): React.ReactNode;
}

const ClassNames: React.FC<ClassNamesProp> = props => {
  const { theme } = useThemeUI();

  return (
    <EmotionClassNames>
      {({ css: emotionCss }) =>
        props.children({
          cssToClassName: styleObject =>
            emotionCss(themeUICss(styleObject)(theme)),
        })
      }
    </EmotionClassNames>
  );
};

export default ClassNames;

With this component, I was able to do this:

<ClassNames>
  {({ cssToClassName }) => (
    <CookieConsent
      declineButtonText="Opt out"
      buttonClasses={cssToClassName({ width: ['100%', 1/2 ] })}
      declineButtonClasses={cssToClassName({ width: ['100%', 1/2 ] })}
      ...
    />
  )}
</ClassNames>

Describe alternatives you've considered

I'm not an expert in frontend technology, so I'm not sure if this is the best way to solve this problem. Any better suggestions would be appreciated.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions