Skip to content

Instantly share code, notes, and snippets.

@tacigar
Created March 19, 2023 16:10
Show Gist options
  • Save tacigar/72edbe4a4fba23f9633256f7022e055c to your computer and use it in GitHub Desktop.
Save tacigar/72edbe4a4fba23f9633256f7022e055c to your computer and use it in GitHub Desktop.
ChatGPTとの問答の末にできたボタンコンポーネント
import React from 'react';
type ButtonAnchorProps = {
href: string;
} & Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'href'>;
type ButtonButtonProps = {
href?: never;
} & React.ButtonHTMLAttributes<HTMLButtonElement>;
type ButtonProps = {
label: string;
} & (ButtonAnchorProps | ButtonButtonProps);
export const Button: React.FC<ButtonProps> = props => {
// href propがあれば、<a>タグをレンダリング
if (props.href) {
const { href, label, ...otherProps } = props;
return (
<a href={href} {...otherProps}>
{label}
</a>
);
}
if ('href' in props) {
return null;
}
// href propがなければ、<button>タグをレンダリング
const { label, ...otherProps } = props;
return (
<button type="button" {...otherProps}>
{label}
</button>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment