Slot
Compose components by merging props into children for flexible API design.
The Slot component enables advanced component composition by merging props from a parent into its immediate child element. It's the core utility behind the asChild pattern, allowing users to swap underlying HTML elements while maintaining functional logic.
Installation
npm install @zayne-labs/ui-reactBasic Usage
This pattern allows a component to "give its identity" to its child.
import { Slot } from "@zayne-labs/ui-react/common/slot";
function Button({ asChild, ...props }) {
const Component = asChild ? Slot.Root : 'button';
return <Component {...props} className="btn" />;
}
// Renders an <a> styled like a button
<Button asChild>
<a href="/login">Login</a>
</Button>Component API
Merges parent props, event handlers, and refs into the first valid React element child it receives.
Slot.Root requires exactly one valid React element child. Text nodes or multiple elements will result in an error or no-render.
A marker component used to indicate which part of the component's children should be preserved when the asChild substitution occurs.
Why use Slot?
- Semantic Flexibility: Allow users to change a
<button>to an<a>or a<div>without breaking styles or interactive logic. - Smart Merging: Automatically concatenates
classNamestrings and mergesstyleobjects. - EventHandler Composition: If both the parent and child have
onClick, both handlers will be executed in sequence.
// Both handlers will run!
<Button asChild={true} onClick={() => console.log("Parent Logger")}>
<button type="button" onClick={() => console.log("Child Action")}>
Click Me
</button>
</Button>Last updated on