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-react

Basic 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>

If your component has required surrounding markup but still needs to be slottable, use Slot.Slottable.

import { Slot } from "@zayne-labs/ui-react/common/slot";

function Card({ asChild, children, ...props }) {
  const Component = asChild ? Slot.Root : 'div';

  return (
    <Component {...props} className="card-outer">
      <div className="card-inner">
        <Slot.Slottable>{children}</Slot.Slottable>
      </div>
    </Component>
  );
}

Component API

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 className strings and merges style objects.
  • 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 onClick={() => console.log("Child Action")}>Click Me</button>
</Button>
Edit on GitHub

Last updated on

On this page