React

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.

<Text as="p">paragraph text</Text>
<Text as="span">inline text</Text>
<Text as="h3">heading text</Text>

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

// FAB uses the button tag by default, but you can change it to a link using asChild.
<FAB asChild>
  <a href="/create">
    <Icon svg={<IconPlusLine />} />
  </a>
</FAB>

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

// You can compose functionality into the Link component provided by a router library.
<Button asChild>
  <Link to="/create">
    <Icon svg={<IconPlusLine />} />
  </Link>
</Button>

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.

// Incorrect way
const MyButton = () => <button />;

// Correct way
const MyButton = (props) => <button {...props} />;

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.

// Incorrect way
const MyButton = (props) => <button {...props} />;

// Correct way
const MyButton = React.forwardRef((props, forwardedRef) => (
  <button {...props} ref={forwardedRef} />
));

While not required in all cases, using React.forwardRef is always the safest approach.

Table of contents