How to use dynamic component names in qwik?

84 Views Asked by At

I wanted to dynamically use either html <button> or qwik <Link> based on whether href prop is present, but the link doesn't seem to work this way and clicking on it does nothing

import { Slot, component$ } from "@builder.io/qwik";
import { Link } from "@builder.io/qwik-city";

interface ButtonProps {
  href?: string;
}

export const Button = component$<ButtonProps>(({ href }) => {
  const Component = href ? Link : "button";

  return (
    <Component class="cursor-pointer select-none bg-blue-600 px-4 py-2 text-white">
      <Slot />
    </Component>
  );
});
1

There are 1 best solutions below

2
Abhay Chaurasia On

Have you tried the traditional way ?

export const Button = component$<ButtonProps>(({ href }) => {
  const Component = href ? Link : "button";

  if(href) {
    return(
        <Link class="cursor-pointer select-none bg-blue-600 px-4 py-2 text-white">
            <Slot />
        </Link>
    );
  } else {
    return(
        <button class="cursor-pointer select-none bg-blue-600 px-4 py-2 text-white">
            <Slot />
        </button>
    );
  }
});