Skip to main content

RadioButtonGroup Component

The RadioButtonGroup component in React is designed for creating a group of radio buttons, allowing users to select one option from a set. It's integrated with react-hook-form for efficient form handling.

Features

  • Dynamically creates a group of radio buttons based on provided options.
  • Seamlessly integrates with react-hook-form.
  • Custom styling for both selected and unselected states.
  • Supports any number of options.

Props

PropTypeDescription
optionsstring[]Array of options to be displayed as radio buttons.
namestringName for the group of radio buttons.
controlanyreact-hook-form control object for managing state.

Component

import React from "react";
import { Controller } from "react-hook-form";

interface RadioButtonGroupProps {
options: string[];
name: string;
control: any;
}

const RadioButtonGroup: React.FC<RadioButtonGroupProps> = ({
options,
name,
control,
}) => {
return (
<div>
{options.map((option, index) => (
<Controller
key={option}
name={name}
control={control}
render={({ field }) => (
<label className="inline-flex items-center mt-3 cursor-pointer">
<input
type="radio"
{...field}
value={option}
className="hidden"
/>
<span
className={`mr-2 flex justify-center items-center rounded-full border-2 border-gray-400 w-5 h-5 align-middle ${
field.value === option
? "bg-blue-500 text-white border-blue-500"
: "bg-white"
}`}
>
{index}
</span>
<span className="text-gray-700">{option}</span>
</label>
)}
/>
))}
</div>
);
};

export default RadioButtonGroup;

Usage

This component is ideal for forms where a single selection is required from multiple options, such as selecting a preferred option, answering a multiple-choice question, etc.

Styling

Styled using Tailwind CSS, it offers a modern and responsive design. The component's appearance can be customized by altering the Tailwind classes within the component.

Accessibility

The component is accessible, with keyboard navigability and focus management. Further accessibility enhancements can be added as needed.

Dependencies

  • React ^17.0.0 or higher
  • react-hook-form ^7.0.0 or higher
  • Tailwind CSS for styling

Notes

  • Ensure that the options prop is provided with the desired choices.
  • The name prop should match the field name in your form setup.

This documentation provides a detailed overview of the RadioButtonGroup component, explaining its features, props, usage, and styling. Customize it according to your project's needs.