|
| 1 | +{/* Copyright 2023 Adobe. All rights reserved. |
| 2 | +This file is licensed to you under the Apache License, Version 2.0 (the "License"); |
| 3 | +you may not use this file except in compliance with the License. You may obtain a copy |
| 4 | +of the License at http://www.apache.org/licenses/LICENSE-2.0 |
| 5 | +Unless required by applicable law or agreed to in writing, software distributed under |
| 6 | +the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS |
| 7 | +OF ANY KIND, either express or implied. See the License for the specific language |
| 8 | +governing permissions and limitations under the License. */} |
| 9 | + |
| 10 | +import {Layout} from '@react-spectrum/docs'; |
| 11 | +export default Layout; |
| 12 | + |
| 13 | +import docs from 'docs:react-aria-components'; |
| 14 | +import {TypeLink} from '@react-spectrum/docs'; |
| 15 | + |
| 16 | +--- |
| 17 | +category: Concepts |
| 18 | +keywords: [aria, accessibility, react, component] |
| 19 | +type: component |
| 20 | +description: React Aria Components is built using a flexible and composable API that you can extend to build new patterns. If you need even more customizability, drop down to the lower level Hook-based API for even more control over rendering and behavior. Mix and match as needed. |
| 21 | +order: 3 |
| 22 | +--- |
| 23 | + |
| 24 | +# Advanced customization |
| 25 | + |
| 26 | +React Aria Components is built using a flexible and composable API that you can extend to build new patterns. If you need even more customizability, drop down to the lower level Hook-based API for even more control over rendering and behavior. Mix and match as needed. |
| 27 | + |
| 28 | +## Contexts |
| 29 | + |
| 30 | +The React Aria Components API is designed around composition. Components are reused between patterns to build larger composite components. For example, there is no dedicated `NumberFieldIncrementButton` or `SelectPopover` component. Instead, the standalone [Button](Button.html) and [Popover](Popover.html) components are reused within [NumberField](NumberField.html) and [Select](Select.html). This reduces the amount of duplicate styling code you need to write and maintain, and provides powerful composition capabilities you can use in your own components. |
| 31 | + |
| 32 | +```tsx |
| 33 | +<NumberField> |
| 34 | + <Label>Width</Label> |
| 35 | + <Group> |
| 36 | + <Input /> |
| 37 | + <Button slot="increment">+</Button> |
| 38 | + <Button slot="decrement">-</Button> |
| 39 | + </Group> |
| 40 | +</NumberField> |
| 41 | +``` |
| 42 | + |
| 43 | +React Aria Components automatically provide behavior to their children by passing event handlers and other attributes via context. For example, the increment and decrement buttons in a `NumberField` receive `onPress` handlers that update the value. Keeping each element of a component separate enables full styling, layout, and DOM structure control, and contexts ensure that accessibility and behavior are taken care of on your behalf. |
| 44 | + |
| 45 | +This architecture also enables you to reuse React Aria Components in your own custom patterns, or even replace one part of a component with your own custom implementation without rebuilding the whole pattern from scratch. |
| 46 | + |
| 47 | +### Custom patterns |
| 48 | + |
| 49 | +Each React Aria Component exports a corresponding context that you can use to build your own compositional APIs similar to the built-in components. 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)). |
| 50 | + |
| 51 | +This example shows a `FieldGroup` component that renders a group of text fields. The entire group can be marked as disabled via the `isDisabled` prop, which is passed to all child text fields via the `TextFieldContext` provider. |
| 52 | + |
| 53 | +```tsx |
| 54 | +import {TextFieldContext} from 'react-aria-components'; |
| 55 | + |
| 56 | +interface FieldGroupProps { |
| 57 | + children?: React.ReactNode, |
| 58 | + isDisabled?: boolean |
| 59 | +} |
| 60 | + |
| 61 | +function FieldGroup({children, isDisabled}: FieldGroupProps) { |
| 62 | + return ( |
| 63 | + /*- begin highlight -*/ |
| 64 | + <TextFieldContext.Provider value={{isDisabled}}> |
| 65 | + {/*- end highlight -*/} |
| 66 | + {children} |
| 67 | + </TextFieldContext.Provider> |
| 68 | + ); |
| 69 | +} |
| 70 | +``` |
| 71 | + |
| 72 | +Any `TextField` component you place inside a `FieldGroup` will automatically receive the `isDisabled` prop from the group, including those that are deeply nested inside other components. |
| 73 | + |
| 74 | +```tsx |
| 75 | +<FieldGroup isDisabled={isSubmitting}> |
| 76 | + <MyTextField label="Name" /> |
| 77 | + <MyTextField label="Email" /> |
| 78 | + <CreditCardFields /> |
| 79 | +</FieldGroup> |
| 80 | +``` |
| 81 | + |
| 82 | +The contexts consumed by each component are listed in the Advanced Customization section of their documentation, along with examples of some potential use cases. |
| 83 | + |
| 84 | +### Slots |
| 85 | + |
| 86 | +Some patterns include multiple instances of the same component. These use the `slot` prop to distinguish each instance. Slots are named children within a component that can receive separate behaviors and [styles](styling.html#slots). Separate props can be sent to slots by providing an object with keys for each slot name to the component's context provider. |
| 87 | + |
| 88 | +This example shows a `Stepper` component with slots for its increment and decrement buttons. |
| 89 | + |
| 90 | +```tsx |
| 91 | +function Stepper({children}) { |
| 92 | + let [value, setValue] = React.useState(0); |
| 93 | + |
| 94 | + return ( |
| 95 | + <ButtonContext.Provider |
| 96 | + value={{ |
| 97 | + slots: { |
| 98 | + increment: { |
| 99 | + onPress: () => setValue(value + 1) |
| 100 | + }, |
| 101 | + decrement: { |
| 102 | + onPress: () => setValue(value - 1) |
| 103 | + } |
| 104 | + } |
| 105 | + }}> |
| 106 | + {children} |
| 107 | + </ButtonContext.Provider> |
| 108 | + ); |
| 109 | +} |
| 110 | + |
| 111 | +<Stepper> |
| 112 | + <Button slot="increment">⬆</Button> |
| 113 | + <Button slot="decrement">⬇</Button> |
| 114 | +</Stepper> |
| 115 | +``` |
| 116 | + |
| 117 | +The slots provided by each built-in React Aria component are shown in the Anatomy section of their documentation. |
| 118 | + |
| 119 | +### Provider |
| 120 | + |
| 121 | +In complex components, you may need to provide many contexts. The `Provider` component is a utility that makes it easier to provide multiple React contexts without manually nesting them. This can be achieved by passing pairs of contexts and values as an array to the `values` prop. |
| 122 | + |
| 123 | +```tsx |
| 124 | +import {Provider, ButtonContext, InputContext} from 'react-aria-components'; |
| 125 | + |
| 126 | +<Provider |
| 127 | + values={[ |
| 128 | + [ButtonContext, {/* ... */}], |
| 129 | + [InputContext, {/* ... */}] |
| 130 | + ]}> |
| 131 | + {/* ... */} |
| 132 | +</Provider> |
| 133 | +``` |
| 134 | + |
| 135 | +This is equivalent to: |
| 136 | + |
| 137 | +```tsx |
| 138 | +<ButtonContext.Provider value={{/* ... */}}> |
| 139 | + <InputContext.Provider value={{/* ... */}}> |
| 140 | + {/* ... */} |
| 141 | + </InputContext.Provider> |
| 142 | +</ButtonContext.Provider> |
| 143 | +``` |
| 144 | + |
| 145 | +### Consuming contexts |
| 146 | + |
| 147 | +You can also consume from contexts provided by React Aria Components in your own custom components. This allows you to replace a component used as part of a larger pattern with a custom implementation. For example, you could consume from `LabelContext` in an existing styled label component to make it compatible with React Aria Components. |
| 148 | + |
| 149 | +#### useContextProps |
| 150 | + |
| 151 | +The <TypeLink links={docs.links} type={docs.exports.useContextProps} /> hook merges the local props and ref with the ones provided via context by a parent component. The local props always take precedence over the context values (following the rules documented in [mergeProps](mergeProps.html)). `useContextProps` supports the [slot](#slots) prop to indicate which value to consume from context. |
| 152 | + |
| 153 | +```tsx |
| 154 | +import type {LabelProps} from 'react-aria-components'; |
| 155 | +import {LabelContext, useContextProps} from 'react-aria-components'; |
| 156 | + |
| 157 | +const MyCustomLabel = React.forwardRef( |
| 158 | + (props: LabelProps, ref: React.ForwardedRef<HTMLLabelElement>) => { |
| 159 | + // Merge the local props and ref with the ones provided via context. |
| 160 | + /*- begin highlight -*/ |
| 161 | + [props, ref] = useContextProps(props, ref, LabelContext); |
| 162 | + /*- end highlight -*/ |
| 163 | + |
| 164 | + // ... your existing Label component |
| 165 | + return <label {...props} ref={ref} />; |
| 166 | + } |
| 167 | +); |
| 168 | +``` |
| 169 | + |
| 170 | +Since it consumes from `LabelContext`, `MyCustomLabel` can be used within any React Aria component instead of the built-in `Label`. |
| 171 | + |
| 172 | +```tsx |
| 173 | +<TextField> |
| 174 | + {/*- begin highlight -*/} |
| 175 | + <MyCustomLabel>Name</MyCustomLabel> |
| 176 | + {/*- end highlight -*/} |
| 177 | + <Input /> |
| 178 | +</TextField> |
| 179 | +``` |
| 180 | + |
| 181 | +#### useSlottedContext |
| 182 | + |
| 183 | +To consume a context without merging with existing props, use the <TypeLink links={docs.links} type={docs.exports.useSlottedContext} /> hook. This works like React's `useContext`, and also accepts an optional slot argument to identify which slot name to consume. |
| 184 | + |
| 185 | +```tsx |
| 186 | +import {useSlottedContext} from 'react-aria-components'; |
| 187 | + |
| 188 | +// Consume the un-slotted value. |
| 189 | +let buttonContext = useSlottedContext(ButtonContext); |
| 190 | + |
| 191 | +// Consume the value for a specific slot name. |
| 192 | +let incrementButtonContext = useSlottedContext(ButtonContext, 'increment'); |
| 193 | +``` |
| 194 | + |
| 195 | +### Accessing state |
| 196 | + |
| 197 | +Most React Aria Components compose other standalone components in their children to build larger patterns. However, some components are made up of more tightly coupled children. For example, [Calendar](Calendar.html) includes children such as `CalendarGrid` and `CalendarCell` that cannot be used standalone, and must appear within a `Calendar` or `RangeCalendar`. These components access the state from their parent via context. |
| 198 | + |
| 199 | +You can access the state from a parent component via the same contexts in order to build your own custom children. This example shows a `CalendarValue` component that displays the currently selected date from a calendar as a formatted string. |
| 200 | + |
| 201 | +```tsx |
| 202 | +import {CalendarStateContext} from 'react-aria-components'; |
| 203 | +import {useDateFormatter} from 'react-aria'; |
| 204 | +import {getLocalTimeZone} from '@internationalized/date'; |
| 205 | + |
| 206 | +function CalendarValue() { |
| 207 | + /*- begin highlight -*/ |
| 208 | + let state = React.useContext(CalendarStateContext)!; |
| 209 | + /*- end highlight -*/ |
| 210 | + let date = state.value?.toDate(getLocalTimeZone()); |
| 211 | + let formatted = date ? useDateFormatter().format(date) : 'None'; |
| 212 | + return `Selected date: ${formatted}`; |
| 213 | +} |
| 214 | +``` |
| 215 | + |
| 216 | +This enables a `<CalendarValue>` to be placed inside a `<Calendar>` to display the current value. |
| 217 | + |
| 218 | +```tsx |
| 219 | +<Calendar> |
| 220 | + {/* ... */} |
| 221 | + {/*- begin highlight -*/} |
| 222 | + <CalendarValue /> |
| 223 | + {/*- end highlight -*/} |
| 224 | +</Calendar> |
| 225 | +``` |
| 226 | + |
| 227 | +The state interfaces and their associated contexts supported by each component are listed in the Advanced Customization section of their documentation. |
| 228 | + |
| 229 | +## Hooks |
| 230 | + |
| 231 | +If you need to customize things even further, such as overriding behavior, intercepting events, or customizing DOM structure, you can drop down to the lower level Hook-based API. Hooks only provide behavior and leave all rendering to you. This gives you more control and flexibility, but requires additional glue code to set up. |
| 232 | + |
| 233 | +React Aria Components and Hooks can be used together, allowing you to mix and match depending on the level of customization you require. We recommend starting with the component API by default, and only dropping down to hooks when you need to customize something that the component API does not allow. |
| 234 | + |
| 235 | +Some potential use cases for Hooks are: |
| 236 | + |
| 237 | +* Overriding which DOM element a component renders |
| 238 | +* Rendering a subset of the children (e.g. virtualized scrolling) |
| 239 | +* Intercepting a DOM event to apply conditional logic |
| 240 | +* Overriding internal state management behavior |
| 241 | +* Customizing overlay positioning |
| 242 | +* Removing unused features to reduce bundle size |
| 243 | + |
| 244 | +### Setup |
| 245 | + |
| 246 | +As described [above](#contexts), each React Aria component exports a corresponding context. You can build a custom implementation of a component using Hooks by consuming from the relevant context with <TypeLink links={docs.links} type={docs.exports.useContextProps} />. |
| 247 | + |
| 248 | +This example shows how a custom checkbox could be set up using `CheckboxContext` from `react-aria-components` and the [useCheckbox](useCheckbox.html) hook from `react-aria`. |
| 249 | + |
| 250 | +```tsx |
| 251 | +import type {CheckboxProps} from 'react-aria-components'; |
| 252 | +import {CheckboxContext, useContextProps} from 'react-aria-components'; |
| 253 | +import {useToggleState} from 'react-stately'; |
| 254 | +import {useCheckbox} from 'react-aria'; |
| 255 | + |
| 256 | +const MyCheckbox = React.forwardRef((props: CheckboxProps, ref: React.ForwardedRef<HTMLInputElement>) => { |
| 257 | + // Merge the local props and ref with the ones provided via context. |
| 258 | + ///- begin highlight -/// |
| 259 | + [props, ref] = useContextProps(props, ref, CheckboxContext); |
| 260 | + ///- end highlight -/// |
| 261 | + |
| 262 | + // Follow the hook docs and implement your customizations... |
| 263 | + let state = useToggleState(props); |
| 264 | + let {inputProps} = useCheckbox(props, state, ref); |
| 265 | + return <input {...inputProps} ref={ref} />; |
| 266 | +}); |
| 267 | +``` |
| 268 | + |
| 269 | +Since `MyCheckbox` consumes from `CheckboxContext` it can be used within other React Aria Components in place of the built-in `Checkbox`, such as within a [Table](Table.html) or [GridList](GridList.html). This lets you provide a custom checkbox implementation without rewriting all other React Aria Components you might use it in. |
| 270 | + |
| 271 | +```tsx |
| 272 | +<GridList> |
| 273 | + <Item> |
| 274 | + {/*- begin highlight -*/} |
| 275 | + <MyCheckbox slot="selection" /> |
| 276 | + {/*- end highlight -*/} |
| 277 | + {/* ... */} |
| 278 | + </Item> |
| 279 | +</GridList> |
| 280 | +``` |
| 281 | + |
| 282 | +### Reusing children |
| 283 | + |
| 284 | +You can also provide values for React Aria Components from a Hook-based implementation. This allows you to customize the parent component of a larger pattern, while reusing the existing implementations of the child elements from React Aria Components. |
| 285 | + |
| 286 | +This example shows how a custom number field could be set up. First, follow the docs for [useNumberField](useNumberField.html), and then use [Provider](#provider) to send values returned by the hook to each of the child elements via their corresponding contexts. |
| 287 | + |
| 288 | +```tsx |
| 289 | +import type {NumberFieldProps} from 'react-aria-components'; |
| 290 | +import {Provider, GroupContext, InputContext, LabelContext, ButtonContext} from 'react-aria-components'; |
| 291 | +import {useNumberFieldState} from 'react-stately'; |
| 292 | +import {useNumberField, useLocale} from 'react-aria'; |
| 293 | + |
| 294 | +function CustomNumberField(props: NumberFieldProps) { |
| 295 | + // Follow the hook docs... |
| 296 | + let {locale} = useLocale(); |
| 297 | + let state = useNumberFieldState({...props, locale}); |
| 298 | + let ref = useRef<HTMLInputElement>(null); |
| 299 | + let { |
| 300 | + labelProps, |
| 301 | + groupProps, |
| 302 | + inputProps, |
| 303 | + incrementButtonProps, |
| 304 | + decrementButtonProps |
| 305 | + } = useNumberField(props, state, ref); |
| 306 | + |
| 307 | + // Provide values for the child components via context. |
| 308 | + return ( |
| 309 | + /*- begin highlight -*/ |
| 310 | + <Provider |
| 311 | + values={[ |
| 312 | + [GroupContext, groupProps], |
| 313 | + [InputContext, {...inputProps, ref}], |
| 314 | + [LabelContext, labelProps], |
| 315 | + [ButtonContext, { |
| 316 | + slots: { |
| 317 | + increment: incrementButtonProps, |
| 318 | + decrement: decrementButtonProps |
| 319 | + } |
| 320 | + }] |
| 321 | + ]}> |
| 322 | + {props.children} |
| 323 | + </Provider> |
| 324 | + /*- end highlight -*/ |
| 325 | + ); |
| 326 | +} |
| 327 | +``` |
| 328 | + |
| 329 | +Because `CustomNumberField` provides values for the `Group`, `Input`, `Label`, and `Button` components via context, the implementations from React Aria Components can be reused. |
| 330 | + |
| 331 | +```tsx |
| 332 | +<CustomNumberField> |
| 333 | + <Label>Width</Label> |
| 334 | + <Group> |
| 335 | + <Input /> |
| 336 | + <Button slot="increment">+</Button> |
| 337 | + <Button slot="decrement">-</Button> |
| 338 | + </Group> |
| 339 | +</CustomNumberField> |
| 340 | +``` |
| 341 | + |
| 342 | +### Examples |
| 343 | + |
| 344 | +The contexts provided and consumed by each component, along with the corresponding hooks, are listed in the Advanced Customization section of their documentation. The corresponding hook docs cover the implementation and APIs of each component in detail. |
| 345 | + |
| 346 | +The [source code](https://github.com/adobe/react-spectrum/tree/main/packages/react-aria-components/src) of React Aria Components can also be a good resource when building a custom implementation of a component. This may help you understand how all of the hooks and contexts fit together. You can also start by copy and pasting the source for a component from React Aria Components into your project, using this as a starting point to make your customizations. |
0 commit comments