File size: 1,587 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
---
title: Composition
description: Learn how to compose components in Chakra UI.
---
## The `as` Prop
Used to change the underlying HTML element that a React component renders. It
provides a straightforward way to change the underlying element while retaining
the component's functionality.
```jsx
<Heading as="h3">Hello, world!</Heading>
```
:::warning
**TypeScript:** The caveat with the `as` prop is that the types of the component
passed to the `as` prop must be compatible with the component's props. We do not
infer the underlying component's props from the `as` prop.
:::
## The `asChild` Prop
Used to compose a component's functionality onto its child element. This
approach, inspired by
[Radix UI](https://www.radix-ui.com/primitives/docs/utilities/slot), offers
maximum flexibility.
```jsx
<Popover.Root>
<Popover.Trigger asChild>
<Button>Open</Button>
</Popover.Trigger>
</Popover.Root>
```
In this example, the `asChild` prop allows the `Button` to be used as the
trigger for the popover.
## Best Practices
To avoid common pitfalls when using the `as` and `asChild` props, there are a
few best practices to consider:
- **Forward Refs:** Ensure that the underlying component forwards the ref passed
to it properly.
- **Spread Props:** Ensure that the underlying component spreads the props
passed to it.
```jsx
const MyComponent = React.forwardRef((props, ref) => {
return <Box ref={ref} {...props} />
})
// with `as` prop
<MyComponent as="button" />
// with `asChild` prop
<Button asChild>
<MyComponent> Click me </MyComponent>
</Button>
```
|