Last active
February 26, 2025 19:44
-
-
Save guilhermerodz/8065ab8953a2b234912c0e5f9b39389b to your computer and use it in GitHub Desktop.
Tailwind Styled Utility inspired by styled-components and emotion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// .vscode/settings.json | |
{ | |
"tailwindCSS.experimental.classRegex": [ | |
["cva\\(([^)]*)\\)", "[\"'`]([^\"'`]*).*?[\"'`]"], | |
["cn\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"], | |
["styled\\(([^)]*)\\)", "(?:'|\"|`)([^']*)(?:'|\"|`)"] | |
], | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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