Skip to content

Commit

Permalink
refactor: better prop mapping
Browse files Browse the repository at this point in the history
  • Loading branch information
khuongduybui committed Sep 26, 2022
1 parent 4eed8d2 commit 0527528
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 25 deletions.
22 changes: 12 additions & 10 deletions components/Button.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ComponentChildren, JSX } from "preact";
import { JSX } from "preact";
import { IS_BROWSER } from "$fresh/runtime.ts";

enum ButtonVariants {
Expand All @@ -11,14 +11,16 @@ enum ButtonVariants {
yellow,
purple,
}

export type ButtonProps = JSX.HTMLAttributes<HTMLButtonElement> & {
extraClass?: string;
variant?: keyof typeof ButtonVariants;
};

export default function Button({ extraClass, variant, ...props }: ButtonProps) {
const classNames = [
extraClass ?? "",
export default function Button(
{ class: extraClass = "", disabled, variant = "default", ...props }:
ButtonProps,
) {
const commonClassNames = [
"focus:(ring-4 outline-none)",
"font-medium",
"rounded-lg",
Expand Down Expand Up @@ -90,16 +92,16 @@ export default function Button({ extraClass, variant, ...props }: ButtonProps) {
"dark:(bg-purple-600 hover:bg-purple-700 focus:ring-purple-900)",
],
};
const variantEnum = ButtonVariants[variant ?? "default"];
const finalClassNames = classNames.concat(
extraClassNamesByVariant[variantEnum],
const classNames = commonClassNames.concat(
extraClassNamesByVariant[ButtonVariants[variant]],
[extraClass],
);

return (
<button
{...props}
disabled={!IS_BROWSER || props.disabled}
class={finalClassNames.join(" ")}
disabled={!IS_BROWSER || disabled}
class={classNames.join(" ")}
/>
);
}
37 changes: 22 additions & 15 deletions components/Page.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
import { ComponentChildren } from "preact";
import { ComponentChildren, JSX } from "preact";
import { Head } from "$fresh/runtime.ts";

export type PageProps = {
children: ComponentChildren;
export type PageProps = JSX.HTMLAttributes<HTMLBodyElement> & {
title?: string;
};

export default function Page({ children, title }: PageProps) {
export default function Page(
{ class: extraClass = "", title, ...props }: PageProps,
) {
const commonClassNames = [
"bg-white",
"text-gray-900",
"dark:(bg-gray-900 text-white)",
];
const classNames = commonClassNames.concat(extraClass);

const head = title
? (
<Head>
<title>{title}</title>
</Head>
)
: null;

return (
<>
{title
? (
<Head>
<title>{title}</title>
</Head>
)
: null}

<body class="bg-white text-gray-900 dark:(bg-gray-900 text-white)">
{children}
</body>
{head}
<body {...props} class={classNames.join(" ")} />
</>
);
}

0 comments on commit 0527528

Please sign in to comment.