How do you create a component with a default Slot and include it in the main layout in Qwik?

155 Views Asked by At

Let's say I want to create my own Link.

const Link = ({ href, style }) => {
    return <a href={href} class={style}>
        <Slot />
    </a>
}

Now I want to use this Link in the Menu of my website, and the Menu component is imported inside the main layout.

// main layout

<Menu />
<Slot />
<Footer />

Here, I get this error:

[vite] Internal server error: can not be rendered because one of its ancestor is already a . This goes against the HTML spec: https://html.spec.whatwg.org/multipage/dom.html#interactive-content

Why does this happen? It's because inside the main layout, we practically included another <Slot /> by including <Menu /> which contains <Link /> components.

So, what do you think we should do here?

If we ask all developers to specify the name of the slot, that's highly inefficient and dirty:

<Link href="/">
    <span q:slot='link'>About us</span>
</Link>

This is very ugly and inefficient. I don't have many slots in my Link component. I have one Slot. I should not be specifying a name for it.

What should I do?

1

There are 1 best solutions below

0
On

The error message suggests that you an 'a'-Link inside another 'a'-Link. My best guess is that another part of your code puts a Link inside a Link or that you should wrap your Link implementation with component$(...).

I think you can switch to the Link from QwikCity. I don't see additional functionality inside your Link implementation.

import { Link } from '@builder.io/qwik-city'
export default component$<unknown>(() => {
  return <Link href="/">text</Link>;
});