Function createSlots()
createSlots<
C>(name:string,defaultValue?:C):SlotSystem<C>
Source: slots.tsx
Creates a context for slots and a provider that renders the slots and provides the context to them.
Communication between the root component and its slots happens via the context. The root component renders the provider returned by this function and passes the context value to it, as well as any slots or children it receives. The provider then renders the children of the root component using SlotsView. Slots can then use the hook to retrieve the context value from the root component.
Type Parameters
C
C
The type of the context value.
Parameters
name
string
The name of the component associated with these slots.
defaultValue?
C
Returns
SlotSystem<C>
A SlotSystem containing the hook and provider component for the slot system.
See
SlotsView
Example
const { useSlotsContext, SlotsProvider } = createSlots<{ value: string, setValue: Dispatch<string> }>("MyComponent");
// By default, the slot renders the value from the context as simple text.
function MyDefaultSlot() {
const { value } = useSlotsContext();
return <p>{value}</p>;
}
// We can create a custom slot with an input field that can change the value via the context.
function MyCustomSlot() {
const { value, setValue } = useSlotsContext();
return <input value={value} onChange={(event) => setValue(event.target.value)}/>;
}
const DEFAULT_SLOTS = { Slot: MyDefaultSlot };
// This is the root component.
function MyComponent({ children, ...slots }: PropsWithSlots<{ Slot: FC }>) {
const [value, setValue] = useState("No value set");
const context = useMemo(() => ({ value, setValue }), [value]);
return <SlotsProvider
context={context}
defaults={DEFAULT_SLOTS}
slots={slots}
>
{children}
</SlotsProvider>;
}We use useMemo() here to avoid re-rendering all slots on every re-render of <MyComponent/>.
Usage
// We can use the component without any props and it will render the default slot.
<MyComponent/>
// We can pass our custom slot to replace the default slot with.
<MyComponent renderSlot={MyCustomSlot}/>
// We can also replace all slots with any content (including slots) by giving the component children.
<MyComponent>
<h1>Hello world</h1>
<MyDefaultSlot/>
<MyCustomSlot/>
</MyComponent>