@crustack/slot
Merges its props onto its immediate child.
The Slot component merges its props onto its immediate child,
enabling flexible prop forwarding and event handling across your components.
This utility is inspired by @radix-ui/react-slot.
Setup
Define and export the Slot component.
Use the strict option to prevent the Slot props from being overriden by the child's props.
See the detailed behavior section for more info.
Examples
1. Enhancing Child Functionality
With the Slot component, you can easily enhance the functionality
of a child element by forwarding props such as event handlers.
Usage:
Here, clicking the button within the Trigger will log a message to the console
and could trigger further functionality, such as opening a modal.
2. Add asChild prop
The Slot component can be used with an asChild prop to replace the underlying HTML element,
making the component highly reusable while maintaining prop merging behavior.
Usage:
In this example, the Button component wraps an anchor tag, allowing the link to inherit button-like behavior while preserving the original anchor styles and attributes.
Detailed behavior
- Event Handlers: props beginning with
onare merged. Child handlers are invoked before the slot handlers. - Styles: The
styleprop is merged. Child styles take precedence and override any conflicting styles from theSlot. - ClassNames: The
classNameprop is also merged. - Other props:
- when
strict: falsethe child's props override those of the slot. - when
strict: truean Error is thrown if both the Slot and the child define the same prop.
- when