astrojs

How to create use and html element prop to determine the element used by and Astro component


I want to create an Astro component that can be any html element the user passes to it in props. I'm not even sure it is possible with Astro components. Something like this, but with the right syntax.

// the component
---
const { as = "div" } = Astro.props;
---
// by default the component is a div, but that can be changed through the prop
<{as}>
  <slot>
</{as}>
// using the component
<Component as="button">
  Click me!
</Component>

Solution

  • Use a variable that starts with a capital letter:

    const { as: As = "div" } = Astro.props;
    ---
    <As>
      <slot>
    </As>
    

    Documentation: https://docs.astro.build/en/basics/astro-syntax/#dynamic-tags