packages/react-aria-components/docs/ColorField.mdx
{/* 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';
<PageDescription>{docs.exports.ColorField.description}</PageDescription>
<HeaderInfo packageData={packageData} componentNames={['ColorField']} sourceData={[ {type: 'W3C', url: 'https://www.w3.org/WAI/ARIA/apg/patterns/spinbutton/'} ]} />
import {ColorField, Label, Input} from 'react-aria-components';
<ColorField defaultValue="#ff0">
<Label>Primary Color</Label>
<Input />
</ColorField>
@import './Button.mdx' layer(button);
@import './Form.mdx' layer(form);
@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;
}
}
}
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.
<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.
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.
ColorField makes use of the following concepts:
<ExampleCard url="forms.html" title="Forms" description="Validating and submitting form data, and integrating with form libraries.">
<Form /> </ExampleCard> </section>A ColorField uses the following components, which may also be used standalone or reused in other components.
<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>{/*
*/}
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" />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.
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" />
A ColorField accepts either a color string or <TypeLink links={docs.links} type={docs.exports.Color} /> object as a value.
By default, ColorField is uncontrolled. You can set a default value using the defaultValue prop.
<MyColorField label="Color" defaultValue="#7f007f" />
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.
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>
</>
);
}
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.
<MyColorField label="Color" name="color" />
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.
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>
</>
);
}
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.
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>
.react-aria-ColorField {
&[data-invalid] {
.react-aria-Input {
border-color: var(--invalid-color);
}
}
.react-aria-FieldError {
font-size: 12px;
color: var(--invalid-color);
}
}
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.
The description slot can be used to associate additional help text with a color field.
<ColorField>
<Label>Color</Label>
<Input />
<Text slot="description">Enter a background color.</Text>
</ColorField>
.react-aria-ColorField {
[slot=description] {
font-size: 12px;
}
}
The isDisabled prop can be used prevent the user from editing the value of the color field.
<MyColorField label="Disabled" defaultValue="#7f007f" isDisabled />
.react-aria-ColorField {
.react-aria-Input {
&[data-disabled] {
border-color: var(--border-color-disabled);
color: var(--text-color-disabled);
}
}
}
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.
<MyColorField label="Read only" isReadOnly value="#7f007f" />
A <Label> accepts all HTML attributes.
An <Input> accepts all props supported by the <input> HTML element.
A <FieldError> displays validation errors.
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.
.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.
<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:
.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.
<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.
A ColorField can be targeted with the .react-aria-ColorField CSS selector, or by overriding with a custom className. It supports the following states:
A Label can be targeted with the .react-aria-Label CSS selector, or by overriding with a custom className.
An Input can be targeted with the .react-aria-Input CSS selector, or by overriding with a custom className. It supports the following states:
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.
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:
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.
function MyInput(props) {
return <Input {...props} className="my-input" />
}
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.
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>
fieldset {
padding: 1.5em;
width: fit-content;
}
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.
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.
<ColorField>
<MyCustomLabel>Value</MyCustomLabel>
<Input />
</ColorField>
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.
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.