Ability to create a class name string from a style object.
See original GitHub issueIs 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.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:6 (5 by maintainers)
Top GitHub Comments
I wanted to propose a workaround I usually use
but your solution is pretty awesome. Nice 😄
You’re totally right, I missed that, thanks! Yep, it’d be cool to have a package, though I’m not interested in contributing it personally. Did you want to reopen @hasparus?