Back to React Spectrum

ColorField

packages/react-aria-components/docs/ColorField.mdx

2022-12-1618.5 KB
Original Source

{/* 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 Anatomy from '/packages/react-aria/docs/color/ColorFieldAnatomy.svg'; 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 Label from '@react-spectrum/docs/pages/assets/component-illustrations/Label.svg'; import Input from '@react-spectrum/docs/pages/assets/component-illustrations/Input.svg'; import Form from '@react-spectrum/docs/pages/assets/component-illustrations/Form.svg'; import {Keyboard} from '@react-spectrum/text'; import {StarterKits} from '@react-spectrum/docs/src/StarterKits';


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

ColorField

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

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

Example

tsx
import {ColorField, Label, Input} from 'react-aria-components';

<ColorField defaultValue="#ff0">
  <Label>Primary Color</Label>
  <Input />
</ColorField>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
@import './Button.mdx' layer(button);
@import './Form.mdx' layer(form);
css
@import "@react-aria/example-theme";

.react-aria-ColorField {
  display: flex;
  flex-direction: column;
  color: var(--text-color);

  .react-aria-Input {
    padding: 0.286rem;
    margin: 0;
    border: 1px solid var(--border-color);
    border-radius: 6px;
    background: var(--field-background);
    font-size: 1.143rem;
    color: var(--field-text-color);
    width: 100%;
    max-width: 12ch;
    box-sizing: border-box;

    &[data-focused] {
      outline: 2px solid var(--focus-ring-color);
      outline-offset: -1px;
    }
  }
}
</details>

Features

The <input type="color"> HTML element can be used to build a color picker, however it is very inconsistent across browsers and operating systems and consists of a complete color picker rather than a single field for editing a hex value or individual color channel. ColorField helps achieve accessible color fields that can be styled as needed.

  • Interactions – Supports entering a value using a keyboard, incrementing and decrementing with the arrow keys, and adjusting the value with the scroll wheel.
  • Validation – Keyboard input is validated as the user types so that only valid characters are accepted. Custom client and server-side validation is also supported.
  • Accessible – Follows the spinbutton ARIA pattern. Extensively tested across many devices and assistive technologies to ensure announcements and behaviors are consistent.

Anatomy

<Anatomy role="img" aria-label="Color field anatomy diagram: Shows a color field component with labels pointing to its parts, including the input, and label elements." />

A color field consists of an input element and a label. It also supports optional description and error message elements, which can be used to provide more context about the field, and any validation messages.

tsx
import {ColorField, Label, Input, Text, FieldError} from 'react-aria-components';

<ColorField>
  <Label />
  <Input />
  <Text slot="description" />
  <FieldError />
</ColorField>

If there is no visual label, an aria-label or aria-labelledby prop must be passed instead to identify the element to screen readers.

Concepts

ColorField makes use of the following concepts:

<section className={styles.cardGroup} data-size="small">

<ExampleCard url="forms.html" title="Forms" description="Validating and submitting form data, and integrating with form libraries.">

<Form /> </ExampleCard> </section>

Composed components

A ColorField uses the following components, which may also be used standalone or reused in other components.

<section className={styles.cardGroup} data-size="small">

<ExampleCard url="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label" title="Label" description="A label provides context for an input element."> <Label /> </ExampleCard>

<ExampleCard url="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input" title="Input" description="An input allows a user to enter a plain text value with a keyboard."> <Input /> </ExampleCard>

</section>

{/*

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 that you can experiment with, or use as a starting point for your own component library.

<StarterKits component="colorfield" />

Reusable wrappers

If you will use a ColorField 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 ColorField and all of its children together into a single component which accepts a label prop, which is passed to the right place. It also shows how to use the description slot to render help text, and FieldError component to render validation errors.

tsx
import type {ColorFieldProps, ValidationResult} from 'react-aria-components';
import {Text, FieldError} from 'react-aria-components';

interface MyColorFieldProps extends ColorFieldProps {
  label?: string,
  description?: string,
  errorMessage?: string | ((validation: ValidationResult) => string)
}

export function MyColorField({label, description, errorMessage, ...props}: MyColorFieldProps) {
  return (
    <ColorField {...props}>
      {label && <Label>{label}</Label>}
      <Input />
      {description && <Text slot="description">{description}</Text>}
      <FieldError>{errorMessage}</FieldError>
    </ColorField>
  );
}

<MyColorField label="Color" />

Value

A ColorField accepts either a color string or <TypeLink links={docs.links} type={docs.exports.Color} /> object as a value.

Uncontrolled

By default, ColorField is uncontrolled. You can set a default value using the defaultValue prop.

tsx
<MyColorField label="Color" defaultValue="#7f007f" />

Controlled

A ColorField can be made controlled. The <TypeLink links={docs.links} type={docs.exports.parseColor} /> function is used to parse the initial color from a hex string, stored in state. The value and onChange props are used to update the value in state when the edits the value.

tsx
import {parseColor} from 'react-aria-components';

function Example() {
  let [color, setColor] = React.useState(parseColor('#7f007f'));
  return (
    <>
      <MyColorField label="Color" value={color} onChange={setColor} />
      <p>Current color value: {color?.toString('hex')}</p>
    </>
  );
}

HTML forms

ColorField supports the name prop for integration with HTML forms. The value will be submitted to the server as a hex color string. When a channel prop is provided, the value will be submitted as a number instead.

tsx
<MyColorField label="Color" name="color" />

Color channel

By default, ColorField allows the user to edit the color as a hex value. When the colorSpace and channel props are provided, ColorField displays the value for that channel formatted as a number instead. Rendering multiple ColorFields together can allow a user to edit a color.

tsx
function Example() {
  let [color, setColor] = React.useState(parseColor('#7f007f'));
  return (
    <>
      <div style={{display: 'flex', gap: 8}}>
        <MyColorField label="Hue" value={color} onChange={setColor} colorSpace="hsl" channel="hue" />
        <MyColorField label="Saturation" value={color} onChange={setColor} colorSpace="hsl" channel="saturation" />
        <MyColorField label="Lightness" value={color} onChange={setColor} colorSpace="hsl" channel="lightness" />
      </div>
      <p>Current color value: {color?.toString('hex')}</p>
    </>
  );
}

Validation

ColorField supports the isRequired prop to ensure the user enters a value, as well as custom validation functions, realtime validation, and server-side validation. It can also be integrated with other form libraries. See the Forms guide to learn more.

To display validation errors, add a <FieldError> element as a child of the ColorField. This allows you to render error messages from all of the above sources with consistent custom styles.

tsx
import {Form, FieldError, Button} from 'react-aria-components';

<Form>
  <ColorField name="color" isRequired>
    <Label>Color</Label>
    <Input />
    <FieldError />
  </ColorField>
  <Button type="submit">Submit</Button>
</Form>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-ColorField {
  &[data-invalid] {
    .react-aria-Input {
      border-color: var(--invalid-color);
    }
  }

  .react-aria-FieldError {
    font-size: 12px;
    color: var(--invalid-color);
  }
}
</details>

By default, FieldError displays default validation messages provided by the browser. See Customizing error messages in the Forms guide to learn how to provide your own custom errors.

Description

The description slot can be used to associate additional help text with a color field.

tsx
<ColorField>
  <Label>Color</Label>
  <Input />
  <Text slot="description">Enter a background color.</Text>
</ColorField>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-ColorField {
  [slot=description] {
    font-size: 12px;
  }
}
</details>

Disabled

The isDisabled prop can be used prevent the user from editing the value of the color field.

tsx
<MyColorField label="Disabled" defaultValue="#7f007f" isDisabled />
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-ColorField {
  .react-aria-Input {
    &[data-disabled] {
      border-color: var(--border-color-disabled);
      color: var(--text-color-disabled);
    }
  }
}
</details>

Read only

The isReadOnly prop makes the ColorField's value immutable. Unlike isDisabled, the ColorField remains focusable and the contents can still be copied. See the MDN docs for more information.

tsx
<MyColorField label="Read only" isReadOnly value="#7f007f" />

Props

ColorField

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

Label

A <Label> accepts all HTML attributes.

Input

An <Input> accepts all props supported by the <input> HTML element.

FieldError

A <FieldError> displays validation errors.

<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary> <PropTable component={docs.exports.FieldError} links={docs.links} /> </details>

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-ColorField {
  /* ... */
}

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

jsx
<ColorField className="my-color-field">
</ColorField>

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-Input[data-focus-visible] {
  /* ... */
}

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.

jsx
<Input className={({isFocused}) => isFocused ? 'border-blue-500' : 'border-gray-600'} />

The states, selectors, and render props for each component used in a ColorField are documented below.

ColorField

A ColorField can be targeted with the .react-aria-ColorField CSS selector, or by overriding with a custom className. It supports the following states:

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

Label

A Label can be targeted with the .react-aria-Label CSS selector, or by overriding with a custom className.

Input

An Input can be targeted with the .react-aria-Input CSS selector, or by overriding with a custom className. It supports the following states:

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

Text

The help text elements within a ColorField can be targeted with the [slot=description] and [slot=errorMessage] CSS selectors, or by adding a custom className.

FieldError

A FieldError can be targeted with the .react-aria-FieldError CSS selector, or by overriding with a custom className. It supports the following render props:

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

Advanced customization

Composition

If you need to customize one of the components within a ColorField, such as Label or Input, in many cases you can create a wrapper component. This lets you customize the props passed to the component.

tsx
function MyInput(props) {
  return <Input {...props} className="my-input" />
}

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).

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

This example shows a FieldGroup component that renders a group of color fields with a title. The entire group can be marked as read only via the isReadOnly prop, which is passed to all child color fields via the ColorFieldContext provider.

tsx
import {ColorFieldContext} from 'react-aria-components';

interface FieldGroupProps {
  title?: string,
  children?: React.ReactNode,
  isReadOnly?: boolean
}

function FieldGroup({title, children, isReadOnly}: FieldGroupProps) {
  return (
    <fieldset>
      <legend>{title}</legend>
      <ColorFieldContext.Provider value={{isReadOnly}}>
        {children}
      </ColorFieldContext.Provider>
    </fieldset>
  );
}

<FieldGroup title="Colors" isReadOnly>
  <MyColorField label="Background" defaultValue="#fff" />
  <MyColorField label="Foreground" defaultValue="#000" />
</FieldGroup>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
fieldset {
  padding: 1.5em;
  width: fit-content;
}
</details>

Custom children

ColorField passes props to its child components, such as the label and input, via their associated contexts. These contexts are exported so you can also consume them in your own custom components. This enables you to reuse existing components from your app or component library together with React Aria Components.

<ContextTable components={['Label', 'Input', 'Text']} docs={docs} />

This example consumes from LabelContext in an existing styled label component to make it compatible with React Aria Components. The <TypeLink links={docs.links} type={docs.exports.useContextProps} /> hook merges the local props and ref with the ones provided via context by ColorField.

tsx
import type {LabelProps} from 'react-aria-components';
import {LabelContext, useContextProps} from 'react-aria-components';

const MyCustomLabel = React.forwardRef((props: LabelProps, ref: React.ForwardedRef<HTMLLabelElement>) => {
  // Merge the local props and ref with the ones provided via context.
  ///- begin highlight -///
  [props, ref] = useContextProps(props, ref, LabelContext);
  ///- end highlight -///

  // ... your existing Label component
  return <label {...props} ref={ref} />;
});

Now you can use MyCustomLabel within a ColorField, in place of the builtin React Aria Components Label.

tsx
<ColorField>
  <MyCustomLabel>Value</MyCustomLabel>
  <Input />
</ColorField>

State

ColorField provides a <TypeLink links={statelyDocs.links} type={statelyDocs.exports.ColorFieldState} /> object to its children via ColorFieldStateContext. This can be used to access and manipulate the ColorField's state.

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 useColorField for more details.