Search code examples
astrojs

How to self reference Astro component


I have this component Astro component (located at "src/components/Menu.astro");

---
export interface MenuItem {
  name: string;
  link: string;
  items?: MenuItem[];
}

export interface Props {
  items: MenuItem[];
  depth: number;
}

const { items, depth } = Astro.props;
---

<ul data-depth={depth}>
  {
    items.map(({ name, link, items: subItems }) => {
      if (subItems && subItems.length > 0) {
        return (
          <li>
            <div class="dropdown">
              {link ? <a href={link}>{name}</a> : <button>{name}</button>}

              <Menu items={subItems} depth={depth + 1} />
            </div>
          </li>
        );
      }

      return (
        <li>
          <a href={link}>{name}</a>
        </li>
      );
    })
  }
</ul>

On line 28 (where the line reads <Menu items={subItems} depth={depth + 1} />) an error thrown saying;

ReferenceError: Menu is not defined

How can I self reference an Astro component in this case? Thanks in advance.

PS: "Menu" is the component file's name.


Solution

  • Astro has a built in method for this called Astro.self that you can use Astro.self

    Example from docs:

    ---
    const { items } = Astro.props;
    ---
    <ul class="nested-list">
      {items.map((item) => (
        <li>
          <!-- If there is a nested data-structure we render `<Astro.self>` -->
          <!-- and can pass props through with the recursive call -->
          {Array.isArray(item) ? (
            <Astro.self items={item} />
          ) : (
            item
          )}
        </li>
      ))}
    </ul>