0
0

More than 3 years have passed since last update.

[React]onClickするたびに配列に要素を追加する

Posted at

はじめに

ラジオボタンを押すと、押した選択肢のvalueが配列に追加するようにしたかった。
方法がわからず、記事を探しても中々見つからず苦労したので、こちらに記録しておきます。

実現したい事

2つのラジオボタングループがある。
それぞれ3つずつ選択肢があり、ユーザーがクリックした選択肢を配列に追加したい。

スクリーンショット (3).png

解決策

const initialValue = Array(selections.length).fill('0');
const [formData, setFormData] = useState<string[]>(initialValue);

    const updateSelections = (index: number, value: string) => {
        const newFormData = formData.slice();
        newFormData[index] = value;
        setFormData(newFormData);
    };

///...
return (
        <div>
            <FormLabel>{data.formLabel}</FormLabel>
            <RadioGroup onChange={(e) => updateSelections(index, e.target.value)}>
                {data.options.map((option) => (
                    <FormControlLabel
                        key={option.value}
                        control={<Radio />}
                        label={option.label}
                        value={option.value}
                        id={option.value}
                    />
                ))}
            </RadioGroup>
        </div>
    );

①formDataを用意
②formDataの初期値を0にする(initialValue)
③onChangeにupdateSelectionsを実行し、index,選択肢のvalueを渡す
 updateSelectionsでは、
 (1)newFormDataによってformDataのコピーを作る。(本物を破壊したくないため)
 (2)newFormData[index]によって、配列・newFormDataのindexの位置にvlue(選択肢の値)を挿入する。
(3)(2)の値をsetFormDataに入れる
④formDataにonClickごとに選択肢の値が追加されるようになる

 
indexを渡すことで、要素を判別できるようになり、複数個追加できるようになった。

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