shadcn/uiのRadioGroupをボタン化して押しやすくする方法について説明します。
ソースコード
RadioGroupコンポーネントのコードは触らずに、CSSで処理します。
SCSS
.buttonGroup { display: flex; flex-direction: row; flex-wrap: wrap; gap: 0.25rem; } // ラジオボタンを非表示 .buttonGroup button[type='button'] { display: none; } // labelをボタン化 .buttonGroup button[type='button']+label { width: 100px; color: #fff; background-color: #888; border: solid 1px #888; text-align: center; cursor: pointer; border-radius: 4px; box-sizing: border-box; padding: 10px; } // チェックが入っているbuttonの次の要素のlabel .buttonGroup button[type='button'][data-state='checked']+label { background: #fff; color: #888; border-color: #888; }
TSX
<RadioGroup className={buttonGroupStyles.buttonGroup} defaultValue='orange' onValueChange={changeValue} > <RadioGroupItem value='apple' id='apple' /><Label htmlFor='apple'>Apple</Label> <RadioGroupItem value='orange' id='orange' /><Label htmlFor='orange'>Orange</Label> <RadioGroupItem value='peach' id='peach' /><Label htmlFor='pieach'>Peach</Label> </RadioGroup >