Back to React Spectrum

Disclosure

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

2022-12-1611.4 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/disclosure'; 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 {Keyboard} from '@react-spectrum/text'; import Anatomy from './DisclosureAnatomy.svg';


category: Navigation keywords: [disclosure, collapse, expand, aria, accordion] type: component

Disclosure

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

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

Example

tsx
import {Disclosure, Button, DisclosurePanel, Heading} from 'react-aria-components';
import {ChevronRight} from 'lucide-react';

<Disclosure>
  <Heading>
    <Button slot="trigger">
      <ChevronRight size={18} />
      System Requirements
    </Button>
  </Heading>
  <DisclosurePanel>
    Details about system requirements here.
  </DisclosurePanel>
</Disclosure>
<details> <summary style={{fontWeight: 'bold'}}><ChevronRight size="S" /> Show CSS</summary>
css
@import "@react-aria/example-theme";
@import './Button.mdx' layer(button);
css
.react-aria-Disclosure {
  .react-aria-Button[slot=trigger] {
    background: none;
    border: none;
    box-shadow: none;
    font-weight: bold;
    font-size: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;

    svg {
      rotate: 0deg;
      transition: rotate 200ms;
      fill: none;
      stroke: currentColor;
      stroke-width: 3px;
    }
  }

  .react-aria-Heading {
    margin: 0;
  }

  &[data-expanded] .react-aria-Button[slot=trigger] svg {
    rotate: 90deg;
  }
}

.react-aria-DisclosurePanel {
  margin-left: 26px;
  height: var(--disclosure-panel-height);
  transition: height 250ms;
  overflow: clip;

  @media (prefers-reduced-motion: reduce) {
    transition: none;
  }
}
</details>

Features

Disclosures can be built with the <details> and <summary> HTML elements, but this can be difficult to style, especially when adding adjacent interactive elements, like buttons, to the disclosure's heading. Disclosure helps achieve accessible disclosures implemented with the correct ARIA pattern while making custom styling easy.

  • Flexible - Structured such that it can be used standalone or combined with other disclosures to form a DisclosureGroup
  • Keyboard Interaction - When focused, a disclosure's visibility can be toggled with either the <Keyboard>Enter</Keyboard> or <Keyboard>Space</Keyboard> key, and the appropriate ARIA attributes are automatically applied.
  • Accessible - Uses hidden="until-found" in supported browsers, enabling find-in-page search support and improved search engine visibility for collapsed content
  • Styleable - Keyboard focus, disabled and expanded states are provided for easy styling. These states only apply when interacting with an appropriate input device, unlike CSS pseudo classes.

Anatomy

<Anatomy />

A disclosure consists of a button and panel of content. The button contains the label representing content within the panel, and the panel is the section of content that is associated with the button which is either expanded or collapsed.

tsx
import {Button, Disclosure, DisclosurePanel, Heading} from 'react-aria-components';

<Disclosure>
  <Heading>
    <Button />
  </Heading>
  <DisclosurePanel />
</Disclosure>

Reusable wrappers

If you will use a Disclosure 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 Disclosure and all of its children together into a single component.

tsx

import type {DisclosureProps} from 'react-aria-components';

interface MyDisclosureProps extends Omit<DisclosureProps, 'children'> {
  title?: string,
  children?: React.ReactNode
}

function MyDisclosure({title, children, ...props}: MyDisclosureProps) {
  return (
    <Disclosure {...props}>
      <Heading>
        <Button slot="trigger">
          <ChevronRight size={18} />
          {title}
        </Button>
      </Heading>
      <DisclosurePanel>
        {children}
      </DisclosurePanel>
    </Disclosure>
  )
}

<MyDisclosure title="Manage your account">
  Details on managing your account
</MyDisclosure>

Expanded

An uncontrolled Disclosure can be expanded by default using the defaultExpanded prop.

tsx
<MyDisclosure title="Download, Install, and Set Up" defaultExpanded>
  Instructions on how to download, install, and set up
</MyDisclosure>

A controlled Disclosure can be expanded and collapsed using isExpanded and onExpandedChange

tsx
function ControlledExpanded() {
  let [isExpanded, setIsExpanded] = React.useState(true);

  return (
    <MyDisclosure title="Download, Install, and Set Up" isExpanded={isExpanded} onExpandedChange={setIsExpanded}>
      Instructions on how to download, install, and set up
    </MyDisclosure>
  )
}

<ControlledExpanded />

Disabled

A Disclosure can be disabled using the isDisabled prop.

tsx
<MyDisclosure title="Introduction to Knitting" isDisabled>
  Details about knitting here
</MyDisclosure>

Interactive elements

In some use cases, you may want to add an interactive element, like a button, adjacent to the disclosure's heading. Please ensure that these elements are siblings of the Heading element and not children.

tsx
<Disclosure>
  <div style={{display: 'flex', alignItems: 'center', gap: 16}}>
    <Heading>
      <Button slot="trigger">
        <ChevronRight size={18} />
        System Requirements
      </Button>
    </Heading>
    <Button>Click me</Button>
  </div>
  <DisclosurePanel>
    Details about system requirements here.
  </DisclosurePanel>
</Disclosure>

Props

Disclosure

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

Button

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

DisclosurePanel

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

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

jsx
<Disclosure className="my-disclosure">
</Disclosure>

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

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
<Disclosure className={({isExpanded}) => isExpanded ? 'border-blue-500' : 'border-gray-600'} />

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

Disclosure

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

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

Use the --disclosure-panel-width and --disclosure-panel-height CSS variables to implement animations.

Button

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

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

DisclosurePanel

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

<StateTable properties={docs.exports.DisclosurePanelRenderProps.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).

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

This example shows a DisclosureGroup component that renders a group of disclosures. The entire group can be marked as disabled via the isDisabled prop, which is passed to all child disclosures via the DisclosureContext provider.

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

interface DisclosureGroupProps {
  children?: React.ReactNode,
  isDisabled?: boolean
}

function DisclosureGroup({children, isDisabled}: DisclosureGroupProps) {
  return (
    <div style={{display: 'flex', flexDirection: 'column'}}>
      <DisclosureContext.Provider value={{isDisabled}}>
        {children}
      </DisclosureContext.Provider>
    </div>
  )
}

<DisclosureGroup isDisabled>
  <MyDisclosure title="How to make a return" >
    Details about returning items
  </MyDisclosure>
  <MyDisclosure title="How to cancel an order" >
    Details on canceling an order
  </MyDisclosure>
</DisclosureGroup>

State

DisclosureGroup provides a <TypeLink links={statelyDocs.links} type={statelyDocs.exports.DisclosureState} /> object to its children via DisclosureStateContext. This can be used to access and manipulate the disclosure group's state.

Hooks

If you need to customize things further, such as accessing internal state or customizing DOM structure, you can drop down to the lower level Hook-based API. See useDisclosure.