技術ブログ

プログラミング、IT関連の記事中心

TypeScriptでよく使う基本機能を含んだButtonコンポーネント

目次

ディレクトリ構造

コンポーネント部分のディレクトリ構造は以下とします。

~/Button
       ┣ index.tsx
       ┗ index.module.css

index.tsx

index.tsx」には以下を記載します。
ボタン表示内容とボタン押下時の処理のみ用意しています。

import styles from "./index.module.css";

const Button = ({
  title = "",
  onClick = () => undefined,
}: Props) => {
  return (
    <button className={styles.button} onClick={onClick}>
      {title}
    </button>
  );
};

type Props = {
  title: string;
  onClick?: () => void;
};

export default Button;

index.module.css

index.module.css」には以下を記載します。
内部には、ボタンのCSSを任意で記載します。

.button {
    ~~~任意のCSS~~~
}

コンポーネントの呼び出し方

利用する箇所で、以下の様にインポートします。
※「~」の部分は環境によって修正してください。

import Button from "~/Button";

以下の様に記載することで、コンポーネントを呼び出す事ができます。

<Button title="ボタン" onClick={() => console.log('button click'} />