Tutorial
Template's as Prop

Template as Prop

By default, when a slot encounters a template element, it renders the template's children within a React.Fragment. You can change the wrapper element to any valid React element using the as prop. Any props you pass to a template with the as prop specified will be applied to that element.

function Child({ children }) {
  const { slot } = useSlot();
  return <slot.default />;
}
 
// Intrinsic elements
<Child>
  <template.default as="div" className="foo">
    Content
  </template.default>
</Child>;
// Expected HTML output:
<div class="foo">Content</div>;
 
// The template element's child function is executed first
<Child>
  <template.default as="h1" id="foo">
    {() => <span>Content</span>}
  </template.default>
</Child>;
// Expected HTML output:
<h1 id="foo">
  <span>Content</span>
</h1>;
 
// Custom components
function Heading({ level, children }) {
  const Element = "h" + level;
  return <Element>{children}</Element>;
}
<Child>
  <template.default as={Heading} level={2}>
    <span>Content</span>
  </template.default>
</Child>;
// Expected HTML output:
<h2>
  <span>Content</span>
</h2>;

Note: Only elements with an available children prop of type ReactNode can be used for the template's as prop.

🚫

Be careful when providing custom components for template's as prop: Template as Custom Component Footgun