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?

clsxの使用例

Posted at

clsxとは何か

clsxは、Reactやその他JavaScriptでよく使用される軽量なユーティリティライブラリである。
cssクラス名を効率的に結合・管理するために使われる。
主に、条件付きでクラス名を切り替えるような場合に便利。

#使用方法

npmやyarnを使ってインストール

npm install clsx

基本的な使用例

import clsx from 'clsx';

function Button({isHighlighted, isDisabled}) {
    return (
        <button className={clsx(
        'default-style',                    //常に適用されているクラス
        isHighlighted && 'highlighted',     //強調されているときに適用
        isDisabled && 'disabled'            //無効化されているときに適用
        )}
        >
          Click Me
        </button>
    );
}

isHighlightedtrueの場合 → highlightedクラスが追加される。
isDisabledtrueの場合 → disabledクラスが追加される。

clsxを使用するメリット

1.コードの可読性向上:クラス名を条件に応じて追加する処理が簡潔になる。
2.エラー回避:無効値を自動的に無視できるので、意図しないクラス適用を防げる。

無効値:nullundefinedfalse、空文字('')

clsxを使用することで、簡潔かつ安全なコードを実現できる。

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?