The complete tutorial for this slot system for react
https://www.breakp.dev/blog/simple-slot-system-for-react/
With this tiny Slot component, you can use slots inside React components.
In addition it supports
- named slots
- default slot
- required slot
- optional fallback element, if the slot is not provided
The Slot component is very small and does all the work.
import { Slot } from "./components";
export function TestContainer({ children } ) {
return (
<div>
<Slot name="header" required children={children} />
<p>content</p>
<Slot children={children} />
<Slot name="footer" fallback={<p>Default Footer</p>} children={children} />
</div>
);
}
The test container:
- requests a "header" slot, required, will error if not provided
- includes the default slot, that is all children non-slotted
- requests a "footer" slot, optional, with fallback content if not provided
import { TestContainer } from "./components";
export function ComplexComponent() {
return (
<TextContainer>
<p slot="header">This will be the header</p>
<p>Other body content</p>
<p>Other body content</p>
<p>Other body content</p>
</TextContainer>
);
}
if you want to avoid using
any
inisValidElement(x) && (x.props as any)?
you can useisValidElement<{slot: string | undefined}>(x) && x.props.slot
instead.