Utilities

Slot

Merges its props onto its immediate child.

Features

    Can be used to support your own `asChild` prop.

Installation

Install the component from your command line.

npm install @radix-ui/react-slot

Anatomy

Import the component.

import { Slot } from '@radix-ui/react-slot';
export default () => (
<Slot>
<div>Hello</div>
</Slot>
);

Basic example

Use to create your own asChild API.

When your component has a single children element:

// your-button.jsx
import React from 'react';
import { Slot } from '@radix-ui/react-slot';
function Button({ asChild, ...props }) {
const Comp = asChild ? Slot : 'button';
return <Comp {...props} />;
}

Use when your component has multiple childrens to pass the props to the correct element:

// your-button.jsx
import React from 'react';
import { Slot, Slottable } from '@radix-ui/react-slot';
function Button({ asChild, leftElement, rightElement, ...props }) {
const Comp = asChild ? Slot : 'button';
return (
<Comp {...props}>
{leftElement}
<Slottable>{children}</Slottable>
{rightElement}
</Comp>
);
}

Usage

import { Button } from './your-button';
export default () => (
<Button asChild>
<a href="/contact">Contact</a>
</Button>
);

Event handlers

Any prop that starts with on (e.g., onClick) is considered an event handler.

When merging event handlers, Slot will create a new function where the child handler takes precedence over the slot handler.

If one of the event handlers relies on event.defaultPrevented make sure that the order is correct.

import { Slot } from '@radix-ui/react-slot';
export default () => (
<Slot onClick={(event) => { if (!event.defaultPrevented) console.log('Not logged because default is prevented.'); }} >
<button onClick={(event) => event.preventDefault()} />
</Slot>
);