Reactでclassnameを条件分岐で付与する方法
※備忘録
Selectタグにはplaceholderがありません。
placeholderをCSSで作る方法はこちら
https://blog.logrocket.com/creating-custom-select-dropdown-css/
・三項演算子を使う方法
Sample.tsx
import {useState} from "react";
import styles from './Sample.module.scss'
const options = [
{optionLabel: "未選択", optionValue: ""},
{optionLabel: "dog", optionValue: "dog"},
{optionLabel: "cat", optionValue: "cat"},
{optionLabel: "hamster", optionValue: "hamster"},
]
export const Sample = () => {
const [selected, setSelected] = useState<string>("")
return (
<>
<select
value={selected}
onChange={(e) => setSelected(e.target.value)}
className={selected === "" ? styles.empty : styles.selected}
>
{options.map((option) => (
<option
key={option.optionValue}
value={option.optionValue}
>
{option.optionLabel}
</option>
))}
</select>
</>
)
}
Sample.module.scss
.empty {
color: gray;
}
.selected {
color: black;
}
・classnamesを使う方法
classnamesをインストール(リンク)
npm install classnames
Sample.tsx
import {useState} from "react";
import styles from './Sample.module.scss'
import classNames from "classnames"
const options = [
{optionLabel: "未選択", optionValue: ""},
{optionLabel: "dog", optionValue: "dog"},
{optionLabel: "cat", optionValue: "cat"},
{optionLabel: "hamster", optionValue: "hamster"},
]
export const Sample = () => {
const [selected, setSelected] = useState<string>("")
return (
<>
<select
value={selected}
onChange={(e) => setSelected(e.target.value)}
className={classNames(styles.selected, {
[styles.empty]: selected === ""
})}
>
{options.map((option) => (
<option
key={option.optionValue}
value={option.optionValue}
>
{option.optionLabel}
</option>
))}
</select>
</>
)
}
Sample.module.scss
.selected {
color: black;
}
.empty {
color: gray;
}
注 .selectedより.emptyが後で読み込まれるようにしている。