Radio Group
A set of checkable buttons—known as radio buttons—where no more than one of the buttons can be checked at a time.
Installation
Install the following dependencies:
npm install @radix-ui/react-radio-groupCopy and paste the following code into your project.
'use client';
import * as RadioGroupPrimitive from '@radix-ui/react-radio-group';
import clsx from 'clsx';
import { Circle } from 'lucide-react';
import { ComponentPropsWithoutRef, ElementRef, forwardRef } from 'react';
import styles from './styles.module.scss';
const RadioGroup = forwardRef<
ElementRef<typeof RadioGroupPrimitive.Root>,
ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Root>
>(({ className, ...props }, ref) => {
return <RadioGroupPrimitive.Root className={clsx(styles.radio__group, className)} {...props} ref={ref} />;
});
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName;
const RadioGroupItem = forwardRef<
ElementRef<typeof RadioGroupPrimitive.Item>,
ComponentPropsWithoutRef<typeof RadioGroupPrimitive.Item>
>(({ className, ...props }, ref) => {
return (
<RadioGroupPrimitive.Item ref={ref} className={clsx(styles.radio__group__item, className)} {...props}>
<RadioGroupPrimitive.Indicator className={styles.radio__group__item__indicator}>
<Circle className={styles.radio__group__item__icon} />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
);
});
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName;
export { RadioGroup, RadioGroupItem };Update the import paths to match your project setup.
Usage
import { Label } from '@/components/ui/label';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';<RadioGroup defaultValue='option-one'>
<div className='flex items-center space-x-2'>
<RadioGroupItem value='option-one' id='option-one' />
<Label htmlFor='option-one'>Option One</Label>
</div>
<div className='flex items-center space-x-2'>
<RadioGroupItem value='option-two' id='option-two' />
<Label htmlFor='option-two'>Option Two</Label>
</div>
</RadioGroup>