# Link

## Introduction

The Link component is a navigational element that allows users to navigate between pages or external resources. Built on Joy UI's Link, it provides consistent styling and accessibility features while supporting various visual styles and text hierarchy levels. Links are fundamental to web navigation and should be used to connect related content within your application.

```tsx
<Link
  children="Link"
  variant="plain"
/>
```

| Field     | Description | Default |
| --------- | ----------- | ------- |
| variant   | —           | "plain" |
| color     | —           | —       |
| level     | —           | —       |
| disabled  | —           | —       |
| underline | —           | —       |

## Usage

```tsx
import { Link } from '@ceed/cds';

function MyComponent() {
  return (
    <div>
      {/* Basic link */}
      <Link href="/about">About Us</Link>

      {/* External link */}
      <Link href="https://example.com" target="_blank" rel="noopener noreferrer">
        External Site
      </Link>

      {/* Styled link */}
      <Link href="/contact" color="primary" underline="hover">
        Contact
      </Link>
    </div>
  );
}
```

## Examples

### Basic Link

The default link appearance with plain variant.

```tsx
<Link
  children="Link"
  variant="plain"
/>
```

### Variants

Links support different visual styles through the variant prop.

```
<Canvas of={Link.Variants} />
```

### Colors

Apply different semantic colors to links.

```
<Canvas of={Link.Colors} />
```

### Underline Styles

Control the underline behavior of links.

```
<Canvas of={Link.Underline} />
```

### Typography Levels

Links can inherit or specify typography levels for different text hierarchies.

```
<Canvas of={Link.Levels} />
```

### Disabled State

Links can be disabled to prevent interaction.

```
<Canvas of={Link.Disabled} />
```

### External Links

Links to external resources with proper security attributes.

```
<Canvas of={Link.ExternalLink} />
```

### Inline with Text

Links can be seamlessly integrated within paragraph text.

```
<Canvas of={Link.InlineWithText} />
```

## When to Use

### ✅ Good Use Cases

- **Page navigation**: Moving between different pages or sections within your app
- **External resources**: Linking to external websites, documentation, or references
- **In-context references**: Linking related content mentioned in text
- **Skip navigation**: Accessibility links for keyboard users
- **Breadcrumbs**: Navigation hierarchy indicators
- **Footer navigation**: Site-wide links in footer sections

### ❌ When Not to Use

- **Actions that don't navigate**: Use Button instead for actions like submitting forms, opening modals, or triggering events
- **Primary calls to action**: Use Button for prominent actions users should take
- **Menu items**: Use MenuItem components within navigation menus
- **Tab navigation**: Use Tabs component for content switching within a page
- **Cards/clickable areas**: Use Card with onClick or a wrapping anchor element

## Common Use Cases

### Navigation Menu Links

```tsx
function NavigationMenu() {
  return (
    <nav>
      <Stack direction="row" spacing={3}>
        <Link href="/" color="neutral" underline="none">
          Home
        </Link>
        <Link href="/products" color="neutral" underline="none">
          Products
        </Link>
        <Link href="/about" color="neutral" underline="none">
          About
        </Link>
        <Link href="/contact" color="neutral" underline="none">
          Contact
        </Link>
      </Stack>
    </nav>
  );
}
```

### Inline Text Links

```tsx
function ArticleContent() {
  return (
    <Typography level="body-md">
      For more information about our services, please visit our{' '}
      <Link href="/services">services page</Link> or read our{' '}
      <Link href="/faq">frequently asked questions</Link>.
    </Typography>
  );
}
```

### External Links with Icon

```tsx
function ExternalResourceLink() {
  return (
    <Link
      href="https://documentation.example.com"
      target="_blank"
      rel="noopener noreferrer"
      endDecorator={<OpenInNewIcon sx={{ fontSize: 16 }} />}
    >
      View Documentation
    </Link>
  );
}
```

### Footer Links

```tsx
function FooterLinks() {
  return (
    <Stack direction="row" spacing={2} divider={<Divider orientation="vertical" />}>
      <Link href="/privacy" level="body-sm" color="neutral">
        Privacy Policy
      </Link>
      <Link href="/terms" level="body-sm" color="neutral">
        Terms of Service
      </Link>
      <Link href="/cookies" level="body-sm" color="neutral">
        Cookie Policy
      </Link>
    </Stack>
  );
}
```

### Link with React Router

```tsx
import { Link as RouterLink } from 'react-router-dom';

function RouterIntegration() {
  return (
    <Link component={RouterLink} to="/dashboard">
      Go to Dashboard
    </Link>
  );
}
```

### Skip to Content Link

```tsx
function SkipLink() {
  return (
    <Link
      href="#main-content"
      sx={{
        position: 'absolute',
        left: '-9999px',
        '&:focus': {
          left: 0,
          zIndex: 1000,
          p: 2,
          bgcolor: 'background.surface',
        },
      }}
    >
      Skip to main content
    </Link>
  );
}
```

### Download Link

```tsx
function DownloadLink({ filename, url }) {
  return (
    <Link
      href={url}
      download={filename}
      startDecorator={<DownloadIcon />}
    >
      Download {filename}
    </Link>
  );
}
```

## Props and Customization

### Key Props

| Prop             | Type                                                           | Default     | Description                              |
| ---------------- | -------------------------------------------------------------- | ----------- | ---------------------------------------- |
| `href`           | `string`                                                       | -           | The URL to navigate to                   |
| `variant`        | `'plain' \| 'outlined' \| 'soft' \| 'solid'`                   | `'plain'`   | Visual style variant                     |
| `color`          | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'` | `'primary'` | Color scheme                             |
| `level`          | `string`                                                       | -           | Typography level (e.g., 'body-md', 'h4') |
| `underline`      | `'none' \| 'hover' \| 'always'`                                | `'hover'`   | Underline behavior                       |
| `disabled`       | `boolean`                                                      | `false`     | Disable the link                         |
| `startDecorator` | `ReactNode`                                                    | -           | Element before the link text             |
| `endDecorator`   | `ReactNode`                                                    | -           | Element after the link text              |
| `component`      | `ElementType`                                                  | `'a'`       | The root element type                    |

### Underline Behavior

```tsx
<Stack spacing={2}>
  {/* No underline */}
  <Link underline="none" href="#">Never underlined</Link>

  {/* Underline on hover (default) */}
  <Link underline="hover" href="#">Underline on hover</Link>

  {/* Always underlined */}
  <Link underline="always" href="#">Always underlined</Link>
</Stack>
```

### With Decorators

```tsx
<Stack spacing={2}>
  <Link href="#" startDecorator={<HomeIcon />}>
    Home
  </Link>

  <Link href="#" endDecorator={<ArrowForwardIcon />}>
    Learn more
  </Link>

  <Link
    href="https://external.com"
    target="_blank"
    endDecorator={<OpenInNewIcon sx={{ fontSize: '1rem' }} />}
  >
    External link
  </Link>
</Stack>
```

### Custom Styling

```tsx
<Link
  href="#"
  sx={{
    fontWeight: 'bold',
    transition: 'color 0.2s',
    '&:hover': {
      color: 'primary.600',
    },
  }}
>
  Custom styled link
</Link>
```

## Accessibility

Link components include comprehensive accessibility features:

### Semantic HTML

- Uses native `<a>` element by default for proper semantics
- Supports custom components for router integration

### Screen Reader Support

- Links announce their destination or purpose
- Use descriptive link text instead of "click here" or "read more"

```tsx
// ✅ Good: Descriptive link text
<Link href="/pricing">View our pricing plans</Link>

// ❌ Bad: Non-descriptive link text
<Link href="/pricing">Click here</Link>
```

### Keyboard Navigation

- **Tab**: Navigate to and from links
- **Enter**: Activate the link
- Links receive visible focus indicators

### External Links

Always include proper attributes for external links:

```tsx
<Link
  href="https://external-site.com"
  target="_blank"
  rel="noopener noreferrer"
  aria-label="Visit external site (opens in new tab)"
>
  External Site
</Link>
```

### Color Contrast

All link colors meet WCAG contrast requirements. Avoid relying solely on color to indicate links - use underlines or other visual indicators.

## Best Practices

### ✅ Do

1. **Use descriptive text**: Link text should describe the destination

```tsx
// ✅ Good
<Link href="/documentation">Read the documentation</Link>

// ❌ Bad
<Link href="/documentation">Click here</Link>
```

2. **Indicate external links**: Show users when links open in new tabs

```tsx
<Link href="https://external.com" target="_blank" rel="noopener noreferrer">
  External Resource <OpenInNewIcon sx={{ fontSize: 14 }} />
</Link>
```

3. **Use appropriate colors**: Match link colors to their context and importance

4. **Maintain consistency**: Use consistent link styles throughout your application

### ❌ Don't

1. **Don't use links for actions**: Use Button for non-navigation actions

```tsx
// ❌ Bad: Using link for action
<Link onClick={handleSubmit}>Submit Form</Link>

// ✅ Good: Using button for action
<Button onClick={handleSubmit}>Submit Form</Button>
```

2. **Don't disable links without reason**: If content is unavailable, explain why

3. **Don't open all external links in new tabs**: Only do so when users might lose context

4. **Don't use link styling for non-interactive elements**

## Performance Considerations

### Prefetching

When using with routing libraries, consider implementing link prefetching for improved perceived performance:

```tsx
// With Next.js
import NextLink from 'next/link';

<Link component={NextLink} href="/page" prefetch>
  Prefetched Page
</Link>
```

### Avoid Unnecessary Re-renders

For links in lists or frequently updating components, ensure stable references:

```tsx
// Using useCallback for event handlers in links
const handleClick = useCallback((e) => {
  trackLinkClick(e);
}, []);

<Link href="/page" onClick={handleClick}>
  Tracked Link
</Link>
```

Link is a fundamental navigation component that ensures consistent, accessible navigation throughout your application. Use it thoughtfully to create clear pathways for users to explore your content.
