Skip to content

Instantly share code, notes, and snippets.

@Gomah
Last active April 22, 2024 23:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gomah/cb2b0b3f7cb9838a0efd6508a42c3eda to your computer and use it in GitHub Desktop.
Save Gomah/cb2b0b3f7cb9838a0efd6508a42c3eda to your computer and use it in GitHub Desktop.
Responsive Variants with CVA, class-variance-authority
import { useMediaQuery } from 'usehooks-ts'
import { useMemo } from 'react';
import resolveConfig from 'tailwindcss/resolveConfig';
import tailwindConfig from '../../tailwind.config';
const fullConfig = resolveConfig(tailwindConfig);
const { screens } = fullConfig.theme;
type Breakpoints = keyof typeof screens;
type ResponsiveValue<T> = T extends boolean ? boolean : T extends string ? T : keyof T;
type ResponsiveProps<T> = {
[K in Breakpoints]?: ResponsiveValue<T>;
} & { initial: ResponsiveValue<T> };
function getScreenValue(key: string) {
return Number.parseInt(screens[key as Breakpoints].replace('px', ''), 10);
}
/**
* Custom hook for handling responsive behavior based on breakpoints.
* @param props - The responsive props containing breakpoints and initial value.
* @returns The responsive value based on the current breakpoint.
*/
export function useResponsiveVariant<T>(props: ResponsiveProps<T>) {
const { initial, ...breakpoints } = props;
const mediaQueries = Object.keys(breakpoints)
.sort((a, b) => getScreenValue(b) - getScreenValue(a))
.map((breakpoint) =>
useMediaQuery(`(min-width: ${screens[breakpoint as Breakpoint]})`)
? breakpoints[breakpoint as Breakpoint]
: undefined
)
.filter((value) => value !== undefined);
const size = useMemo(() => {
return mediaQueries[0] ?? initial;
}, [initial, mediaQueries]);
return size as ResponsiveValue<T>;
}
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
outline:
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-10 px-4 py-2",
sm: "h-9 rounded-md px-3",
lg: "h-11 rounded-md px-8",
icon: "h-10 w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }
import { Button, ButtonProps } from '@/ui';
function Example() {
const buttonSize = useResponsiveVariant<ButtonProps['size']>({ initial: 'sm', sm: 'lg' });
return <Button size={buttonSize}>Button</Button>
}
@mnzsss
Copy link

mnzsss commented Apr 22, 2024

Great solution, thanks!

@Gomah
Copy link
Author

Gomah commented Apr 22, 2024

Great solution, thanks!

@mnzsss You're welcome, I made a quick revision as it wasn't fully working with boolean values ✌️

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