Back to React Spectrum

ColorSlider

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

2022-12-1623.2 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/ColorSliderAnatomy.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 {Keyboard} from '@react-spectrum/text'; import {StarterKits} from '@react-spectrum/docs/src/StarterKits';


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

ColorSlider

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

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

Example

tsx
import {ColorSlider, ColorThumb, Label, SliderOutput, SliderTrack} from 'react-aria-components';

<ColorSlider channel="hue" defaultValue="hsl(0, 100%, 50%)">
  <Label />
  <SliderOutput />
  <SliderTrack>
    <ColorThumb />
  </SliderTrack>
</ColorSlider>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-ColorSlider {
  display: grid;
  grid-template-areas: "label output"
                       "track track";
  grid-template-columns: 1fr auto;
  gap: 4px;
  width: 100%;
  max-width: 300px;

  .react-aria-Label {
    grid-area: label;
    color: var(--text-color);
  }

  .react-aria-SliderOutput {
    grid-area: output;
    width: 4ch;
    text-align: end;
    color: var(--text-color);
  }

  .react-aria-SliderTrack {
    grid-area: track;
    border-radius: 4px;
  }

  &[data-orientation=horizontal] {
    .react-aria-SliderTrack {
      height: 28px;
    }

    .react-aria-ColorThumb {
      top: 50%;
    }
  }
}

.react-aria-ColorThumb {
  border: 2px solid white;
  box-shadow: 0 0 0 1px black, inset 0 0 0 1px black;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  box-sizing: border-box;

  &[data-focus-visible] {
    width: 24px;
    height: 24px;
  }
}
</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 color channel slider. ColorSlider helps achieve accessible and touch-friendly color sliders that can be styled as needed.

  • Customizable – Support for adjusting a single channel of RGBA, HSLA, and HSBA colors, in both horizontal and vertical orientations.
  • High quality interactions – Mouse, touch, and keyboard input is supported via the useMove hook. Pressing the track moves the thumb to that position. Text selection and touch scrolling are prevented while dragging.
  • Accessible – Announces localized color descriptions for screen reader users (e.g. "dark vibrant blue"). Uses a visually hidden <input> element for mobile screen reader support and HTML form integration.
  • International – Channel value is formatted according to the user's locale. The color slider automatically mirrors all interactions in right-to-left languages.

Anatomy

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

A color slider consists of a track element and a thumb that the user can drag to change a single channel of a color value. It may also include optional label and <output> elements to display the color channel name and current numeric value, respectively. A visually hidden <input> element is used to represent the value to assistive technologies.

tsx
import {ColorSlider, ColorThumb, Label, SliderOutput, SliderTrack} from 'react-aria-components';

<ColorSlider>
  <Label />
  <SliderOutput />
  <SliderTrack>
    <ColorThumb />
  </SliderTrack>
</ColorSlider>

Composed components

A ColorSlider 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>

</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="colorslider" />

Reusable wrappers

If you will use a ColorSlider 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 ColorSlider and all of its children together into a single component which accepts an optional label prop, which is passed to the right place. It also shows how to use the defaultStyle render prop to add a checkerboard pattern behind partially transparent gradients.

tsx
import type {ColorSliderProps} from 'react-aria-components';

interface MyColorSliderProps extends ColorSliderProps {
  label?: string
}

export function MyColorSlider({label, ...props}: MyColorSliderProps) {
  return (
    <ColorSlider {...props}>
      <Label>{label}</Label>
      <SliderOutput />
      <SliderTrack
        style={({defaultStyle}) => ({
          background: `${defaultStyle.background},
            repeating-conic-gradient(#CCC 0% 25%, white 0% 50%) 50% / 16px 16px`
        })}>
        <ColorThumb />
      </SliderTrack>
    </ColorSlider>
  );
}

<MyColorSlider label="Red Opacity" defaultValue="#f00" channel="alpha" />

Value

A ColorSlider requires either an uncontrolled default value or a controlled value, provided using the defaultValue or value props respectively. The value provided to either of these props should be a color string or <TypeLink links={docs.links} type={docs.exports.Color} /> object. The channel prop must also be provided to specify which color channel the slider should display. This must be one of the channels included in the color value, for example, for RGB colors, the "red", "green", and "blue" channels are available. For a full list of supported channels, see the Props table below.

Controlled

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 to make the ColorSlider controlled, and updated in the onChange event.

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

function Example() {
  let [value, setValue] = React.useState(parseColor('hsl(0, 100%, 50%)'));
  return (
    <>
      <MyColorSlider
        label="Hue (controlled)"
        value={value}
        onChange={setValue}
        channel="hue" />
      <p>Value: {value.toString('hex')}</p>
    </>
  );
}

HTML forms

ColorSlider supports the name prop for integration with HTML forms. The value will be submitted as a number between the minimum and maximum value for the displayed channel.

tsx
<MyColorSlider
  defaultValue="#7f0000"
  channel="red"
  name="red" />

Events

ColorSlider supports two events: onChange and onChangeEnd. onChange is triggered whenever the ColorSlider's handle is dragged, and onChangeEnd is triggered when the user stops dragging the handle. Both events receive a <TypeLink links={docs.links} type={docs.exports.Color} /> object as a parameter.

The example below uses onChange and onChangeEnd to update two separate elements with the ColorSlider's value.

tsx
function Example() {
  let [currentValue, setCurrentValue] = React.useState(parseColor('hsl(50, 100%, 50%)'));
  let [finalValue, setFinalValue] = React.useState(currentValue);

  return (
    <div>
      <MyColorSlider
        value={currentValue}
        channel="hue"
        onChange={setCurrentValue}
        onChangeEnd={setFinalValue} />
      <p>Current value: {currentValue.toString('hsl')}</p>
      <p>Final value: {finalValue.toString('hsl')}</p>
    </div>
  );
}

Creating a color picker

RGBA

This example shows how you could build an RGBA color picker using four color sliders bound to the same color value in state. The <TypeLink links={docs.links} type={docs.exports.parseColor} /> function is used to parse the initial color from a hex value, stored in state. The value and onChange props of ColorSlider are used to make the sliders controlled, so that they all update when the color is modified.

tsx
function Example() {
  let [color, setColor] = React.useState(parseColor('#ff00ff'));

  return (
    <>
      <MyColorSlider channel="red" value={color} onChange={setColor} />
      <MyColorSlider channel="green" value={color} onChange={setColor} />
      <MyColorSlider channel="blue" value={color} onChange={setColor} />
      <MyColorSlider channel="alpha" value={color} onChange={setColor} />
    </>
  );
}

HSLA

This example shows how to build a similar color picker to the one above, using HSLA colors instead.

tsx
function Example() {
  let [color, setColor] = React.useState(parseColor('hsla(0, 100%, 50%, 0.5)'));

  return (
    <>
      <MyColorSlider channel="hue" value={color} onChange={setColor} />
      <MyColorSlider channel="saturation" value={color} onChange={setColor} />
      <MyColorSlider channel="lightness" value={color} onChange={setColor} />
      <MyColorSlider channel="alpha" value={color} onChange={setColor} />
    </>
  );
}

HSBA

This example shows how to build an HSBA color picker.

tsx
function Example() {
  let [color, setColor] = React.useState(parseColor('hsba(0, 100%, 50%, 0.5)'));
  return (
    <>
      <MyColorSlider channel="hue" value={color} onChange={setColor} />
      <MyColorSlider channel="saturation" value={color} onChange={setColor} />
      <MyColorSlider channel="brightness" value={color} onChange={setColor} />
      <MyColorSlider channel="alpha" value={color} onChange={setColor} />
    </>
  );
}

Visual options

Vertical orientation

Sliders are horizontally oriented by default. The orientation prop can be set to "vertical" to create a vertical slider. This example also hides the visual label. By default, an aria-label is provided using the localized channel name (e.g. Hue).

tsx
<MyColorSlider
  orientation="vertical"
  defaultValue="hsb(0, 100%, 100%)"
  channel="hue" />
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-ColorSlider {
  &[data-orientation=vertical] {
    height: 150px;
    display: block;

    .react-aria-Label,
    .react-aria-SliderOutput {
      display: none;
    }

    .react-aria-SliderTrack {
      width: 28px;
      height: 100%;
    }

    .react-aria-ColorThumb {
      left: 50%;
    }
  }
}

</details>

Disabled

A ColorSlider can be disabled using the isDisabled prop. This prevents the thumb from being focused or dragged. It's up to you to style your color slider to appear disabled accordingly.

tsx
<MyColorSlider channel="red" defaultValue="#7f007f" isDisabled />
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-ColorSlider {
  &[data-disabled] {
    .react-aria-SliderTrack {
      background: gray !important;
    }

    .react-aria-ColorThumb {
      background: gray !important;
      opacity: 0.5;
    }
  }
}
</details>

Labeling

By default, ColorSlider provides an aria-label for the localized color channel name. If a <Label> element is rendered, its children default to the channel name. If you wish to override this with a more specific label, custom children can be provided to the <Label>, or an aria-label or aria-labelledby prop may be passed instead.

tsx
<ColorSlider channel="hue" defaultValue="hsl(0, 100%, 50%)">
  <Label>Background Hue</Label>
  <SliderOutput />
  <SliderTrack>
    <ColorThumb />
  </SliderTrack>
</ColorSlider>
<ColorSlider
  /*- begin highlight -*/
  aria-label="Background Saturation"
  /*- end highlight -*/
  channel="saturation"
  defaultValue="hsl(0, 100%, 50%)">
  <SliderTrack>
    <ColorThumb />
  </SliderTrack>
</ColorSlider>

Accessibility

The aria-valuetext of the <input> element is formatted according to the user's locale automatically. It also includes a localized description of the selected color (e.g. "dark vibrant blue").

Internationalization

In right-to-left languages, color sliders should be mirrored. The label should be right aligned, and the value should be left aligned. Orientation of the gradient background, positioning of the thumb, and dragging behavior is automatically mirrored by ColorSlider.

Props

ColorSlider

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

Label

A <Label> accepts all HTML attributes.

SliderOutput

A <SliderOutput> renders the current value of the color slider as text.

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

SliderTrack

The <SliderTrack> component renders a gradient representing the colors that can be selected for the color channel, and contains a <ColorThumb> element.

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

ColorThumb

The <ColorThumb> component renders a draggable thumb with a preview of the selected color.

<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show props</summary> <PropTable component={docs.exports.ColorThumb} 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-ColorSlider {
  /* ... */
}

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

jsx
<ColorSlider className="my-color-slider">
</ColorSlider>

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-ColorThumb[data-dragging] {
  /* ... */
}

.react-aria-ColorThumb[data-focused] {
  /* ... */
}

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
<ColorThumb className={({isDragging}) => isDragging ? 'scale-150' : 'scale-100'} />

Render props may also be used as children to alter what elements are rendered based on the current state. For example, you could implement custom formatting for the slider's current value.

jsx
<SliderOutput>
  {state => `Value: ${state.getThumbValueLabel(0)}`}
</SliderOutput>

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

ColorSlider

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

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

Label

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

SliderOutput

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

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

SliderTrack

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

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

ColorThumb

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

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

Advanced customization

Composition

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

tsx
function MySliderOutput(props) {
  return <SliderOutput {...props} className="my-slider-output" />
}

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={['ColorSlider']} docs={docs} />

This example shows a ColorSliderDescription component that accepts a color slider in its children and renders a description element below it. It uses the useId hook to generate a unique id for the description, and associates it with the color slider via the aria-describedby attribute passed to the ColorSliderContext provider.

tsx
import {ColorSliderContext} from 'react-aria-components';
import {useId} from 'react-aria';

interface ColorSliderDescriptionProps {
  children?: React.ReactNode,
  description?: string
}

function ColorSliderDescription({children, description}: ColorSliderDescriptionProps) {
  let descriptionId = useId();
  return (
    <div>
      <ColorSliderContext.Provider value={{'aria-describedby': descriptionId}}>
        {children}
      </ColorSliderContext.Provider>
      <small id={descriptionId}>{description}</small>
    </div>
  );
}

<ColorSliderDescription description="It's not easy being green.">
  <MyColorSlider channel="green" defaultValue="#006" />
</ColorSliderDescription>

Custom children

ColorSlider passes props to its child components, such as the label, 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']} 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 ColorSlider.

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 ColorSlider, in place of the builtin React Aria Components Label.

tsx
<ColorSlider>
  <MyCustomLabel>Opacity</MyCustomLabel>
  <SliderTrack>
    <ColorThumb />
  </SliderTrack>
</ColorSlider>

State

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

This example shows a ColorNumberField component that can be placed within a ColorSlider to allow the user to enter a number and update the channel value.

tsx
import {ColorSliderStateContext, LabelContext, NumberField, Input, useSlottedContext} from 'react-aria-components';

function ColorNumberField({channel}) {
  /*- begin highlight -*/
  let state = React.useContext(ColorSliderStateContext)!;
  /*- end highlight -*/
  let labelProps = useSlottedContext(LabelContext)!;
  return (
    <NumberField
      aria-labelledby={labelProps.id}
      value={state.value.getChannelValue(channel)}
      minValue={state.value.getChannelRange(channel).minValue}
      maxValue={state.value.getChannelRange(channel).maxValue}
      onChange={v => state.setValue(state.value.withChannelValue(channel, v))}
      formatOptions={state.value.getChannelFormatOptions(channel)}>
      <Input />
    </NumberField>
  );
}

<ColorSlider channel="hue" defaultValue="hsl(0, 100%, 50%)">
  <Label />
  <ColorNumberField channel="hue" />
  <SliderTrack>
    <ColorThumb />
  </SliderTrack>
</ColorSlider>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
.react-aria-Input {
  width: 4ch;
}
</details>

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