I designed my radio buttons to ensure they cannot be selected multiple times

I have developed a basic React custom controlled radio button:

export const Radio: FC<RadioProps> = ({
  label,
  checked,
  onChange,
  disabled,
}) => {
  const id = useId();

  return (
    <div>
      <label
        htmlFor={id}
        className={clsx(
          disabled ? 'cursor-not-allowed' : 'cursor-pointer',
          'inline-flex items-center mr-4'
        )}
      >
        <input
          onChange={onChange} // This will be used to check the radio button
          type="radio"
          disabled={disabled}
          id={id}
          className="hidden"
        />
        <div
          className={clsx(
            checked ? 'after:scale-1' : 'after:scale-0',
            'radio__radio w-5 h-5 border-2 border-gray-400 rounded-full mr-2 box-border p-0.5',
            "after:content-[''] after:block after:h-full after:w-full after:bg-green-500 after:rounded-full after:transform after:transition-transform after:duration-[35ms]"
          )}
        />
        {label}
      </label>
    </div>
  );
};

Currently, I am displaying a collection of these radio buttons:

<div>
  {items.map(({ label, id }) => {
    return (
      <Radio
        key={id}
        label={label}
        checked={id === selected}
        onChange={() => onSelect(id)}
      />
    );
  })}
</div>

The issue at hand is that the onChange event for each radio button (within the input) triggers only once, preventing users from reselecting a radio button. Users can switch between them but are unable to re-select one, as the onChange in each button fires only once. How can I modify my Radio component to trigger the onChange when reselecting a radio button?

Answer №1

In order for the HTML input element to function properly, you must include both the onChange and checked properties. Make sure to pass the checked property into your <input /> element like this:

const MyCheckableItem = ({ checked, onChange }) => {
  return <input checked={checked} onChange={onChange} />
}

To learn more about this, visit: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#checked

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we ensure that the Material-UI <Select> component is as wide as the widest <MenuItem>?

I am attempting to adjust a Mui Select field so that it is the same width as its largest MenuItem. Despite trying to utilize the autoWidth prop on the Select component, I have not been able to achieve the desired result. To better illustrate the issue, I h ...

What is the best way to increase the padding in a Colorbox modal window?

Is there a way to increase the padding in a Colorbox modal window? I want some extra space between the edges of the modal window and the actual content. I experimented with the innerWidth and innerHeight properties, but unfortunately, I didn't notice ...

Creating a dynamic shift in background color

Is it possible to use jQuery to slowly change the color of diagonal lines in a background styled with CSS, while also adding a fading effect? I have created a fiddle with the necessary CSS to display a static background. You can view it here: http://jsfid ...

Unusual CSS inconsistencies between running on VS Web Server and IIS

My current dilemma involves a discrepancy in the appearance of my site when viewed locally through the visual studio web server (http://localhost:3452/) compared to when accessed on IIS7 (http://server/myproject/). Initially, I suspected a CSS issue causi ...

Changing the text alignment to justify in OWA - HTML emails

Having trouble navigating the Outlook Web App (OWA)? It seems like there are countless issues with different Outlook clients, but OWA is definitely the most poorly documented one. The snippet of code below functions flawlessly in all email clients such as ...

Optimizing images for CSS background in Next.js

How can I efficiently optimize background images in styled-components using Next.js new feature, without relying on the Image component? ...

Make the div stretch across the entire width of the page, excluding the width of a fixed div located on the right side, without needing to set a margin-right property

I've been struggling to find a solution for my wiki development project. My challenge involves designing a page layout with a fixed-width sidebar on the right, while ensuring that content to the left of the sidebar adjusts its width accordingly. I wan ...

avoidable constructor in a react component

When it comes to specifying initial state in a class, I've noticed different approaches being used by people. class App extends React.Component { constructor() { super(); this.state = { user: [] } } render() { return <p>Hi</p> ...

Implementing optional default values in React props using conditional types

I have a dilemma with conditional props types When attempting to set a default value for my optional prop within the conditional type, it causes issues with the types export type ChatBase = { id: string; title: string; } type ChatCardProps = { title: ...

React- Error: Unhandled Type Mismatch in function call for _this4.getNotes

As I delve into learning React, I've created a basic application to manage notes with titles and descriptions. This application interacts with a REST API built using Go, enabling me to perform operations like retrieving, editing, creating, and deleti ...

Mastering React-Table: Learn how to optimize your Material-UI table by implementing useResizeColumns alongside a sticky header feature

Is there a way to implement column resizing in a Material-UI table using the latest version (7.5.x) of React-Table without compromising the 'Sticky Header' functionality? The dilemma arises when attempting to enable column resizing with either & ...

What is the best method for sending the styled and checked option via email?

Just finished customizing the checkboxes on my contact form at cleaners.se/home. Here's my question: If I select "telefon," how can I ensure that this option is sent to my email? In Contact Form 7, I used to simply type a shortcode. Is there a simila ...

Implementing CSS styles according to user preferences. Switching between dark mode and light mode based on subscription

Is there a way to dynamically change CSS property values based on user interaction, such as toggling between dark mode and light mode? I am currently exploring the option of setting up a subscription to track these changes, but I want to know how I can act ...

What feature in React Native allows the use of local folders as a 'package name'?

Hey there, I have a bit of an odd question that I think you can help me with! So in React Native, you have the ability to create a package.json file within your config folder. The contents may look something like this: { "name": "@config" } After addi ...

Slider MIA - Where Did it Go?

I'm having an issue with my slider. When I load the page, it doesn't show the first image until I click the button to load it. How can I make it display the first image by default? Below is my JavaScript code: <script> var slideIndex = 1 ...

Leveraging RTK query with a modular structure allows for seamless integration of multiple APIs within a single component, ensuring that the previous URL and

Currently, I am utilizing RTK query with a modular structure which eliminates the need to manually write endpoints for each URL. However, there is an issue where if two API calls are made within the same component, the most recent call will override the pr ...

Display a progress bar in an application to visualize the loading of database records

Within my application, I am accepting a numerical input that is used to generate results on a separate page. The process involves running multiple sequential JDBC queries against Oracle database tables, resulting in a significant delay (1-2 minutes) for th ...

Issue with Redux-form's type prop not functioning as expected with checkbox and radio components

Hey there, I'm new to working with redux forms and I've been trying to figure out how to use input types other than "text". I've read through the documentation but for some reason, types like "checkbox" or "radio" are not showing up in the b ...

What is the most effective way to implement a single modal throughout my web application without having to duplicate HTML code on each page?

After realizing I was repetitively adding the same div to every page for a modal dialog, I decided to place a single div in the site.master page and call it when needed. This method worked fine until I began implementing ajax with partial page updates. H ...

Experiencing problems with various React Carousel libraries when it comes to displaying

I have been attempting to integrate Carousel libraries into my react app, but I am encountering a common issue with all of them. The Carousels show the items on the first slide, but subsequent slides do not display any items, even though they exist within ...