Link
The Link component is a customizable anchor element that provides consistent styling and behavior across the application. It supports different variants and sizes to fit various design needs.
Usage
import Link from '@/components/Link';
function MyComponent() {
return (
<>
<Link href="/about">About</Link>
<Link href="/contact" variant="selected" size="large">Contact</Link>
</>
);
}
Component Code
import React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const linkVariants = cva(
'transition-colors duration-200',
{
variants: {
variant: {
default: 'text-gray-600 hover:text-gray-900 hover:underline',
selected: 'text-gray-900 font-medium pointer-events-none',
},
size: {
small: 'text-sm',
medium: 'text-base',
large: 'text-lg',
},
},
defaultVariants: {
variant: 'default',
size: 'medium',
},
}
);
export interface LinkProps
extends React.AnchorHTMLAttributes<HTMLAnchorElement>,
VariantProps<typeof linkVariants> {
href: string;
children: React.ReactNode;
}
const Link: React.FC<LinkProps> = ({
href,
children,
variant,
size,
className,
...props
}) => {
return (
<a
href={href}
className={cn(linkVariants({ variant, size, className }))}
{...props}
>
{children}
</a>
);
};
export default Link;
Props
href
(string, required): The URL the link points tovariant
('default' | 'selected'): The style variant of the linksize
('small' | 'medium' | 'large'): The size of the link textclassName
(string, optional): Additional CSS classes- All other props are passed to the underlying
<a>
element
Installation
To use the Link component, you need to install and configure the following dependencies:
React
React should already be installed in your Next.js project. If not, install it:
npm install react react-dom
class-variance-authority
Install class-variance-authority:
npm install class-variance-authority
clsx and tailwind-merge
These are used in the cn utility function. Install them:
npm install clsx tailwind-merge
Tailwind CSS
Ensure Tailwind CSS is installed and configured in your project. If not, follow these steps:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
Then, update your tailwind.config.js:
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
'./app/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {},
},
plugins: [],
}
cn Utility Function
Create a utils.ts file in your lib folder with the following content:
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
After setting up these dependencies and configurations, you can use the Link component as shown in the usage example above.