Skip to content

Instantly share code, notes, and snippets.

@guilhermerodz
Last active February 26, 2025 19:44
Show Gist options
  • Save guilhermerodz/8065ab8953a2b234912c0e5f9b39389b to your computer and use it in GitHub Desktop.
Save guilhermerodz/8065ab8953a2b234912c0e5f9b39389b to your computer and use it in GitHub Desktop.
Tailwind Styled Utility inspired by styled-components and emotion
// .vscode/settings.json
{
"tailwindCSS.experimental.classRegex": [
["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"],
["cn\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"],
["styled\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"]
],
}
import React from 'react';
import { cn } from '@/lib/cn';
export function styled<
C extends keyof React.JSX.IntrinsicElements | React.ComponentType<any>,
>(baseComponent: C, className?: string) {
const Component = React.forwardRef<
React.ComponentRef<C>,
React.ComponentPropsWithRef<C>
>(({ className: classNameToOverride, ...props }, ref) => {
return React.createElement(baseComponent, {
className: cn(className, classNameToOverride),
ref,
...props,
});
});
// Prevent component from showing as `Anonymous` (improves debugging)
Component.displayName =
typeof baseComponent === 'string'
? baseComponent
: baseComponent.displayName || 'Styled';
return Component as unknown as C; // Keep the type of the original component
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment