LoginSignup
3
2

More than 1 year has passed since last update.

React ラジオボタンを正しく実装する

Last updated at Posted at 2022-11-30

上手くいかないパターン

Bootstrap#Radioサンプルコードを貼り付けて1つのラジオボタンに checked 属性をつけた状態

import React, { useState } from "react";

const RadioButton = () => {
    /** 選択中のラジオボタンvalue */
    const [selected, setSelected] = useState("chocolate");
    /** ラジオボタン切り替えイベント */
    const changeValue = (event) => setSelected(event.target.value);

    return (
        <div className="form-check">
            <span>
                <input id="chocolate" className="form-check-input" type="radio" name="sweets" value="chocolate" checked onChange={changeValue}/>
                <label htmlFor="#chocolate" className="form-check-label">
                    チョコレート
                </label>
            </span>
            <span>
                <input id="cake" className="form-check-input" type="radio" name="sweets" value="cake" onChange={changeValue}/>
                <label htmlFor="#cake" className="form-check-label">
                    ケーキ
                </label>
            </span>
            <span>
                <input id="pie" className="form-check-input" type="radio" name="sweets" value="pie" onChange={changeValue}/>
                <label htmlFor="#pie" className="form-check-label">
                    パイ
                </label>
            </span>
            <div>{selected}が選択されました!</div>
        </div>
    )
}
export default RadioButton;

ラジオボタンの切り替えがおかしい

このコードだと、、ケーキをクリックしても選択状態はチョコレートのまま!!
スクリーンショット 2022-12-01 1.37.25.png

上手くいくパターン

こんな手順でラジオボタンを修正しました

  1. ラジオボタンのvalueとラベル値を管理するinterfaceを定義
    1. ラジオボタンの挙動自体とは関係なさそうですが、可読性を高めるために!
  2. interfaceの型に合うようにラジオボタンの定義をする(変数 radioButtons
  3. ラジオボタンを map() でループさせて表示するようにする
  4. ラジオボタンの checked 属性に「ラジオボタン.valueと選択中の状態 selected が一致するか」という条件をつける
import React, { useState } from "react";

/** ラジオボタン設定 */
interface Radio {
    label: string
    value: string
}

const RadioButton = () => {
    /** 選択中のラジオボタンvalue */
    const [selected, setSelected] = useState("chocolate");
    /** ラジオボタン切り替えイベント */
    const changeValue = (event: React.ChangeEvent<HTMLInputElement>) => setSelected(event.target.value);
    /** ラジオボタン */
    const radioButtons: Radio[] = [
        {
            label: "チョコレート",
            value: "chocolate"
        },
        {
            label: "ケーキ",
            value: "cake"
        },
        {
            label: "パイ",
            value: "pie"
        }
    ]

    return (
        <div className="container form-check">
            <div className="row">
            {radioButtons.map(radio => {
                return (
                    <div className="col-4">
                        {/* checked属性に式を定義する */}
                        <input className="form-check-input" type="radio" name="sweets" 
                            value={radio.value} checked={radio.value === selected} onChange={changeValue}/>
                        <label className="form-check-label">
                            <span className="fs-6">{radio.label}</span>
                        </label>
                    </div>
                )
            })}
            </div>
            <div>{selected}が選択されました!</div>
        </div>
    )
}
export default RadioButton;

Reactラジオボタンの完成!

これで正しく動作するラジオボタンができました〜ぱちぱち
スクリーンショット 2022-12-01 1.56.29.png

3
2
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
3
2