0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【props】classNameを複数追加する方法

Posted at

効率よくpropsを渡す

ボタンコンポーネントのようなものを作っていて、それを別のコンポーネントで使い回すとします。

そうすると、**「ここのボタンの色は赤で」****「こっちの文字色は白にして」**などCSSをそれぞれ少しずつ変更させる必要が出てきたりします。

そんなとき、こちらの方法を知っていると**”効率的”**にCSSを変更できるようになります。

Classnames

Classnamesを使って、複数のclassNameをpropsで渡してみました。

Button.tsx
import React from "react";
import styles from "./Button.module.scss";
import classNames from "classnames";

interface PropsTypes {
  backgroundColor?: "primary" | "gray";
  border?: "none";
  fontWeight: "bold";
  textColor?: "white" | "black";
  onClick: React.MouseEventHandler<HTMLParagraphElement> | undefined;
  text: string;
}
const Button = ({
  backgroundColor,
  border,
  fontWeight,
  onClick,
  text,
  textColor,
}: PropsTypes) => {
  return (
    <div
      className={classNames( // ココからclassNames関連
        styles.root,
        { [styles.primary]: backgroundColor === "primary" },
        { [styles.gray]: backgroundColor === "gray" },
        { [styles.borderNone]: border === "none" },
        { [styles.fontWeight]: fontWeight === "bold" },
        { [styles.black]: textColor === "black" },
        { [styles.white]: textColor === "white" }
      )}
    >
      <p onClick={onClick}>{text}</p>
    </div>
  );
};

export default Button;
Button.module.scss
.root {
  border: 1px solid rgb(180, 180, 180);
  border-radius: 5px;
  cursor: pointer;
  color: rgb(121, 121, 121);
  display: flex;
  font-size: 0.6rem;
  padding: 5px;
  p {
    width: 100%;
  }
}
//----- propsCSS -----//
.borderNone {
  border: none;
}
.black {
  color: black;
}
.fontWeight {
  font-weight: bold;
}
.primary {
  background-color: #05c757;
}
.gray {
  background-color: #e5e5e5;
}
.white {
  color: white;
}

このように記述することによって、たとえば別のコンポーネントで<Button>コンポーネントを呼び出す時に、

sample.tsx
<Button
  backGroundColor={"primary"}
  fontWeight={"bold"}
  // その他省略
/>

このようにpropsで値を渡してあげると、その値に合ったCSSが適用されるようになります。

まとめ

Classnamesというライブラリは知らなかったのですが、いろんなclassNameのpropsを渡したい時に重宝しそうです。

また、propsの渡し方がまだまだ無駄があることが多いので、そのあたりもしっかり学びなおして行こうと思います。

追記

現在Coadmapというサービスを使って学習しているのですが、そちらの添削サービスにて添削を受けた内容を、今回の記事としてまとめてみました。

実務で実際に使われているコードの書き方だったりを学べるので、とてもいいサービスだと思います。
ぜひ興味のある方は、サイトを覗いてみてください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?