{/* Copyright 2020 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License. */}

import {Layout} from '@react-spectrum/docs';
export default Layout;

import docs from 'docs:react-aria-components';
import typesDocs from 'docs:@react-types/shared/src/events.d.ts';
import {PropTable, HeaderInfo, TypeLink, PageDescription, StateTable, ContextTable} from '@react-spectrum/docs';
import styles from '@react-spectrum/docs/src/docs.css';
import packageData from 'react-aria-components/package.json';
import Anatomy from '/packages/react-aria/docs/datepicker/daterangepicker-anatomy.svg';
import ChevronRight from '@spectrum-icons/workflow/ChevronRight';
import {Divider} from '@react-spectrum/divider';
import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard';
import {Keyboard} from '@react-spectrum/text';
import {StarterKits} from '@react-spectrum/docs/src/StarterKits';

---
category: Navigation
keywords: [link, anchor, aria]
type: component
---

# Link

<PageDescription>{docs.exports.Link.description}</PageDescription>

<HeaderInfo
  packageData={packageData}
  componentNames={['Link']}
  sourceData={[
    {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/link/'}
  ]} />

## Example

```tsx example
import {Link} from 'react-aria-components';

<Link href="https://www.imdb.com/title/tt6348138/" target="_blank">
  The missing link
</Link>
```

<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
@import "@react-aria/example-theme";

.react-aria-Link {
  color: var(--link-color);
  font-size: 18px;
  transition: all 200ms;
  text-decoration: underline;
  cursor: pointer;
  outline: none;
  position: relative;

  &[data-hovered] {
    text-decoration-style: wavy;
  }

  &[data-pressed] {
    color: var(--link-color-pressed);
  }

  &[data-focus-visible]:after {
    content: '';
    position: absolute;
    inset: -3px -6px;
    border-radius: 6px;
    border: 2px solid var(--focus-ring-color);
  }
}
```

</details>

## Features

Links can be created in HTML with the [&lt;a&gt;](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a)
element with an `href` attribute. However, if the link does not have an href, and is
handled client side with JavaScript instead, it will not be exposed to assistive technology properly.
`Link` helps achieve accessible links with either native HTML elements or custom element types.

* **Flexible** – Support for HTML navigation links, JavaScript handled links, and client side routing. Disabled links are also supported.
* **Accessible** – Implemented as a custom ARIA link when handled via JavaScript, and otherwise as a native HTML link.
* **Styleable** – Hover, press, and keyboard focus states are provided for easy styling. These states only apply when interacting with an appropriate input device, unlike CSS pseudo classes.

## Anatomy

A link consists of a pressable area usually containing a textual label or an icon
that users can click or tap to navigate to another page or resource. In addition,
keyboard users may activate links using the <Keyboard>Enter</Keyboard> key.

If a visual label is not provided (e.g. an icon or image only link), then an `aria-label` or
`aria-labelledby` prop must be passed to identify the link to assistive technology.

## Starter kits

To help kick-start your project, we offer starter kits that include example implementations of all React Aria components with various styling solutions. All components are fully styled, including support for dark mode, high contrast mode, and all UI states. Each starter comes with a pre-configured [Storybook](https://storybook.js.org/) that you can experiment with, or use as a starting point for your own component library.

<StarterKits component="link" />

## Content

Links accept content as children. If the link has an href prop, it will be rendered as an `<a>` element.

```tsx example
<Link href="https://adobe.com" target="_blank">Adobe.com</Link>
```

### JavaScript handled links

When a `<Link`> does not have an `href` prop, it is rendered as a `<span role="link">` instead of an `<a>`. Events will need to be handled in JavaScript with the `onPress` prop.

Note: this will not behave like a native link. Browser features like context menus and open in new tab will not apply.

```tsx example
<Link onPress={() => alert('Pressed link')}>Adobe</Link>
```

## Events

`Link` supports user interactions via mouse, keyboard, and touch. You can handle all of these via the `onPress` prop. This is similar to the standard `onClick` event, but normalized to support all interaction methods equally. In addition, the `onPressStart`, `onPressEnd`, and `onPressChange` events are fired as the user interacts with the link.

Each of these handlers receives a <TypeLink links={typesDocs.links} type={typesDocs.exports.PressEvent} />, which exposes information about the target and the type of event that triggered the interaction. See [usePress](usePress.html) for more details.

```tsx example
function Example() {
  let [pointerType, setPointerType] = React.useState('');

  return (
    <>
      <Link
        onPressStart={e => setPointerType(e.pointerType)}
        onPressEnd={() => setPointerType('')}>
        Press me
      </Link>
      <p>{pointerType ? `You are pressing the link with a ${pointerType}!` : 'Ready to be pressed.'}</p>
    </>
  )
}
```

### Client side routing

The `<Link>` component works with frameworks and client side routers like [Next.js](https://nextjs.org/) and [React Router](https://reactrouter.com/en/main). As with other React Aria components that support links, this works via the <TypeLink links={docs.links} type={docs.exports.RouterProvider} /> component at the root of your app. See the [client side routing guide](routing.html) to learn how to set this up.

## Disabled

A link can be disabled by passing the `isDisabled` property. This will work with both native
link elements as well as client handled links. Native navigation will be disabled, and the `onPress`
event will not be fired. The link will be exposed as disabled to assistive technology with ARIA.

```tsx example
<Link isDisabled href="https://adobe.com" target="_blank">Disabled link</Link>
```


<details>
  <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>

```css
.react-aria-Link {
  &[data-disabled] {
    cursor: default;
    color: var(--text-color-disabled);
  }
}
```

</details>

## Props

<PropTable component={docs.exports.Link} links={docs.links} />

## Styling

React Aria components can be styled in many ways, including using CSS classes, inline styles, utility classes (e.g. Tailwind), CSS-in-JS (e.g. Styled Components), etc. By default, all components include a builtin `className` attribute which can be targeted using CSS selectors. These follow the `react-aria-ComponentName` naming convention.

```css
.react-aria-Link {
  /* ... */
}
```

A custom `className` can also be specified on any component. This overrides the default `className` provided by React Aria with your own.

```jsx
<Link className="my-link">
  {/* ... */}
</Link>
```

In addition, some components support multiple UI states (e.g. focused, placeholder, readonly, etc.). React Aria components expose states using data attributes, which you can target in CSS selectors. For example:

```css
.react-aria-Link[data-pressed] {
  /* ... */
}
```

The `className` and `style` props also accept functions which receive states for styling. This lets you dynamically determine the classes or styles to apply, which is useful when using utility CSS libraries like [Tailwind](https://tailwindcss.com/).

```jsx
<Link className={({isPressed}) => isPressed ? 'bg-gray-700' : 'bg-gray-600'} />
```

Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could render an extra element when the link is in a pressed state.

```jsx
<Link>
  {({isPressed}) => (
    <>
      {isPressed && <PressHighlight />}
      Press me
    </>
  )}
</Link>
```

The states, selectors, and render props for `Link` are documented below.

<StateTable properties={docs.exports.LinkRenderProps.properties} />

## Advanced customization

### Contexts

All React Aria Components export a corresponding context that can be used to send props to them from a parent element. This enables you to build your own compositional APIs similar to those found in React Aria Components itself. You can send any prop or ref via context that you could pass to the corresponding component. The local props and ref on the component are merged with the ones passed via context, with the local props taking precedence (following the rules documented in [mergeProps](mergeProps.html)).

<ContextTable components={['Link']} docs={docs} />

This example shows a `Router` component that accepts `Link` elements as children and keeps track of which one was last clicked.

```tsx example render=false export=true
import type {PressEvent} from 'react-aria-components';
import {LinkContext} from 'react-aria-components';

function Router({children}) {
  let [clicked, setClicked] = React.useState(null);
  let onPress = (e: PressEvent) => {
    setClicked(e.target.textContent);
  };

  return (
    /*- begin highlight -*/
    <LinkContext.Provider value={{onPress}}>
    {/*- end highlight -*/}
      {children}
      {clicked && `You clicked ${clicked}`}
    </LinkContext.Provider>
  );
}
```

Now any `Link` inside a `Router` will update the router state when it is pressed.

```tsx example
<Router>
  <ul>
    <li><Link>Breadcrumbs</Link></li>
    <li><Link>Button</Link></li>
    <li><Link>Calendar</Link></li>
  </ul>
</Router>
```

```css hidden
ul:not([class]) {
  padding: 0px;
}
```

### Hooks

If you need to customize things further, such as customizing the DOM structure, you can drop down to the lower level Hook-based API. See [useLink](useLink.html) for more details.
