Composition
Explains the methods and principles for composing complex UIs by combining components.
as Prop
The as prop is used to change the base HTML element that a React component renders. It provides a simple way to change the base element while maintaining the component's functionality.
asChild Prop
The asChild prop is used to compose a component's functionality into child elements. You can use it to change HTML tags or inject functionality into other components.
It provides the same functionality as the asChild pattern provided by Radix UI.
Changing Element Type
When changing the base element type, it is the developer's responsibility to ensure that the element maintains accessibility and functions correctly. For example, if you change a button to a
div, it may no longer be keyboard accessible.
Combining with React Components
When composing components using asChild, you must follow two principles.
1. The component must spread props
asChild passes its own props and event handlers to provide functionality and maintain accessibility. If the component does not support these props, it will not work correctly.
It is good practice to always spread all props to child components of asChild.
2. The component must forward refs
You may need to pass a ref to the component (for example, to measure element size). If the component does not accept ref, it may not work correctly.
While not required in all cases, using React.forwardRef is always the safest approach.