Skip to content

Instantly share code, notes, and snippets.

@dejurin
Last active March 8, 2024 13:51
Show Gist options
  • Save dejurin/2e0e0a6f209040f43b88a555ca9601dd to your computer and use it in GitHub Desktop.
Save dejurin/2e0e0a6f209040f43b88a555ca9601dd to your computer and use it in GitHub Desktop.
Qwik Polymorphic Component Example
import type { QwikIntrinsicElements } from "@builder.io/qwik";
import { component$, Slot } from "@builder.io/qwik";
export default component$(
<C extends keyof QwikIntrinsicElements>(props: PolyProps<C>) => {
const Component = (props.as ?? "div") as string;
return (
<Component {...props}>
<Slot />
</Component>
);
}
);
export type PolyProps<C extends keyof QwikIntrinsicElements> =
QwikIntrinsicElements[C] & {
as?: C;
};
// These all work with correct types
/*
<>
<Poly>Hello from a div</Poly>
<Poly as="a" href="/blog">Blog</Poly>
<Poly as="input" onInput$={(ev, el) => console.log(el.value)} />
// <Poly as={OtherComponent} someProp /> @todo
</>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment