A flexible and customizable Radio Group component for selecting one option from a list.
Vertical Radio Group
Horizontal Radio Group
Radio Group is a useful component for selecting one option from a list.
// /components/radio-group/radio-group.tsx
import React, { useState } from "react";
interface RadioGroupOption {
label: string;
value: string;
}
interface RadioGroupProps {
options: RadioGroupOption[]; // Array of radio options
name: string; // Name for the radio group
selectedValue?: string; // Initially selected value
onChange?: (value: string) => void; // Callback when the selected value changes
direction?: "horizontal" | "vertical"; // Orientation of radio buttons
}
const radioStyles = {
container: "flex",
vertical: "flex-col space-y-2",
horizontal: "flex-row space-x-4",
radioItem: "flex items-center space-x-2 cursor-pointer",
radioInput: "h-4 w-4 text-blue-600 border-gray-300 focus:ring-blue-500",
radioLabel: "text-zinc-300",
};
const RadioGroup: React.FC<RadioGroupProps> = ({
options,
name,
selectedValue,
onChange,
direction = "vertical",
}) => {
const [selected, setSelected] = useState(selectedValue || "");
const handleSelection = (value: string) => {
setSelected(value);
if (onChange) onChange(value);
};
return (
<div
className={`${radioStyles.container} ${
direction === "vertical" ? radioStyles.vertical : radioStyles.horizontal
}`}
>
{options.map((option) => (
<label key={option.value} className={radioStyles.radioItem}>
<input
type="radio"
name={name}
value={option.value}
checked={selected === option.value}
onChange={() => handleSelection(option.value)}
className={radioStyles.radioInput}
/>
<span className={radioStyles.radioLabel}>{option.label}</span>
</label>
))}
</div>
);
};
export { RadioGroup }