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?

ReactでSelectタグにplaceholderのようなものを実装

Last updated at Posted at 2024-10-10

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が後で読み込まれるようにしている。

0
0
2

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?