{/* Copyright 2024 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 statelyDocs from 'docs:@react-stately/color';
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 ChevronRight from '@spectrum-icons/workflow/ChevronRight';
import {Divider} from '@react-spectrum/divider';
import {ExampleList} from '@react-spectrum/docs/src/ExampleList';
import {ExampleCard} from '@react-spectrum/docs/src/ExampleCard';
import {Keyboard} from '@react-spectrum/text';
import {StarterKits} from '@react-spectrum/docs/src/StarterKits';

---
category: Color
keywords: [color swatch, color picker, aria]
type: component
---

# ColorSwatch

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

<HeaderInfo
  packageData={packageData}
  componentNames={['ColorSwatch']}
  sourceData={[
    {type: 'W3C', url: 'https://w3c.github.io/aria/#img'}
  ]} />

## Example

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

<ColorSwatch color="#f00" />
```

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

```css hidden
@import "./ColorSlider.mdx";
```

```css
.react-aria-ColorSwatch {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
}
```

</details>

## Features

A color swatch may seem simple to build with a `<div>`, but requires additional semantics and labeling for accessibility.

* **Accessible** – Includes a localized color description for screen reader users (e.g. "dark vibrant blue"). Uses the [img](https://w3c.github.io/aria/#img) role with a custom `aria-roledescription` of "color swatch".
* **International** – Accessible color description and role description are translated into over 30 languages.

## Anatomy

A color swatch consists of a color preview, which is exposed to assistive technology with a localized color description.

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

<ColorSwatch />
```

{/*

## Examples

<ExampleList tag="colorslider" />

*/}

## 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="colorswatch" />

## Reusable wrappers

If you will use a ColorSwatch in multiple places in your app, you can wrap all of the pieces into a reusable component. This way, the DOM structure, styling code, and other logic are defined in a single place and reused everywhere to ensure consistency.

This example wraps `ColorSwatch` and shows how to use the `color` [render prop](styling.html#render-props) to add a checkerboard pattern behind partially transparent colors.

```tsx example export=true
import type {ColorSwatchProps} from 'react-aria-components';

export function MyColorSwatch(props: ColorSwatchProps) {
  return (
    <ColorSwatch 
      {...props}
      style={({color}) => ({
        background: `linear-gradient(${color}, ${color}),
          repeating-conic-gradient(#CCC 0% 25%, white 0% 50%) 50% / 16px 16px`
      })} />
  );
}

<MyColorSwatch color="#f00a" />
```

## Value

ColorSwatch accepts a value via the `color` prop. The value should be a color string or <TypeLink links={docs.links} type={docs.exports.Color} /> object.

In the example below, the <TypeLink links={docs.links} type={docs.exports.parseColor} /> function is used to parse the initial color from an HSL string. This is passed to the `value` prop of a [ColorSlider](ColorSlider.html), and the `color` prop of a `ColorSwatch` to show a preview of the selected color.

```tsx example
import {parseColor, ColorSlider, SliderTrack, ColorThumb} from 'react-aria-components';

function Example() {
  let [color, setColor] = React.useState(parseColor('hsl(0, 100%, 50%)'));
  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 8}}>
      <ColorSlider value={color} onChange={setColor} channel="hue">
        <SliderTrack>
          <ColorThumb />
        </SliderTrack>
      </ColorSlider>
      <MyColorSwatch color={color} />
    </div>
  );
}
```

## Labeling

By default, ColorSwatch includes a localized color description for screen reader users (e.g. "dark vibrant blue") as an `aria-label`. If you have a more specific color name (e.g. Pantone colors), the automatically generated color description can be overridden via the `colorName` prop. An additional label describing the context of the color swatch (e.g. "Background color") can also be provided via the `aria-label` or `aria-labelledby` props.

In the example below, the full accessible name of the color swatch will be "Fire truck red, Background color".

```tsx example
<MyColorSwatch color="#f00" aria-label="Background color" colorName="Fire truck red" />
```

## Props

<PropTable component={docs.exports.ColorSwatch} 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-ColorSwatch {
  /* ... */
}
```

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

```jsx
<ColorSwatch className="my-color-swatch">
  {/* ... */}
</ColorSwatch>
```

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
<ColorSwatch style={({color}) => ({background: color.toString('css')})} />
```

The render props for `ColorSwatch` are documented below.

<StateTable properties={docs.exports.ColorSwatchRenderProps.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={['ColorSwatch']} docs={docs} />

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

<ColorSwatchContext.Provider value={{color: '#ff0'}}>
  <ColorSwatch />
</ColorSwatchContext.Provider>
```

### Hooks

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