Button

Displays a button or a component that looks like a button.

Installation

Install the following dependencies:

npm install @radix-ui/react-slot class-variance-authority

Copy and paste the following code into your project.

import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import clsx from 'clsx';
import { ButtonHTMLAttributes, forwardRef } from 'react';
import styles from './styles.module.scss';
 
const buttonVariants = cva(styles.base, {
    variants: {
        variant: {
            default: styles.variant__default,
            destructive: styles.variant__destructive,
            outline: styles.variant__outline,
            secondary: styles.variant__secondary,
            ghost: styles.variant__ghost,
            link: styles.variant__link,
        },
        size: {
            default: styles.size__default,
            sm: styles.size__small,
            lg: styles.size__large,
            icon: styles.size__icon,
        },
    },
    defaultVariants: {
        variant: 'default',
        size: 'default',
    },
});
 
export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement>, VariantProps<typeof buttonVariants> {
    asChild?: boolean;
}
 
const Button = forwardRef<HTMLButtonElement, ButtonProps>(
    ({ className, variant, size, asChild = false, ...props }, ref) => {
        const Comp = asChild ? Slot : 'button';
        return <Comp className={clsx(buttonVariants({ variant, size, className }))} ref={ref} {...props} />;
    }
);
Button.displayName = 'Button';
 
export { Button, buttonVariants };

Update the import paths to match your project setup.

Usage

import { Button } from '@/components/ui/button';
<Button variant='outline'>Button</Button>

You can use the buttonVariants helper to create a link that looks like a button.

import { buttonVariants } from '@/components/ui/button';
<Link className={buttonVariants({ variant: 'outline' })}>Click here</Link>

Alternatively, you can set the asChild parameter and nest the link component.

<Button asChild>
    <Link href='/login'>Login</Link>
</Button>

Examples

Primary

Secondary

Destructive

Outline

Ghost

Icon

As Child