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

What is the best way to make the current tab stand out?

I have implemented a TabHeader component to create a dynamic Tab Menu that displays table contents based on months. The loop runs from the current month back to January, and the content is updated dynamically through an API call triggered by changes in the ...

Hide and show submenus with jQuery while ensuring that the initial submenu remains visible, along with the main menu

I am struggling to figure out how to make the first message active by default along with its corresponding menu selection in my navbar. I have implemented a show/hide functionality on the main menu click, but currently only the menu is being set as active ...

I'm debating on where to dispatch my redux

Currently, I am delving into the world of React and Redux, and a question has been nagging at me. Should I dispatch and share my Redux store in individual components that need it, or would it be better to centralize it in one main component and pass down t ...

What are the benefits of removing event listeners in Reactjs?

In my opinion, the event listeners need to be reliable and consistent. React.useEffect(() => { const height = window.addEventListener("resize", () => { setWindowSize(window.innerHeight); }); return () => window.remov ...

Unusual default Nav bar positioning

When attempting to create a navbar, I encountered small gaps that seemed impossible to close. Adjusting margins only resulted in new gaps appearing on the opposite side. Even when trying to find a compromise, I ended up with gaps on both sides instead. It ...

Is it possible to target elements based on a specific CSS3 property they use?

Is there a method to target all elements in the DOM with a border-radius other than 0? If anyone has suggestions, it would be greatly appreciated! ...

It seems that the memoization feature in Redux's createSelector is not functioning properly

I've been diving into the documentation for createSelector and it seems like its purpose is to cache results in order to avoid repeated expensive computations. However, I am noticing that my console.logs are being triggered in functions where they sho ...

Error encountered when transitioning to TypeScript: Unable to resolve '@/styles/globals.css'

While experimenting with the boilerplate template, I encountered an unusual issue when attempting to use TypeScript with the default NextJS configuration. The problem arose when changing the file extension from .js to .tsx / .tsx. Various versions of NextJ ...

Issue: Assertion violation: The use of <Link> element is restricted to within a <Router>. Any solutions or suggestions?

In my React and Next Js application, I am utilizing react-router-dom for routing purposes. The dependencies listed in the package.json file are as follows: This is how my current package.json file looks: { "name": "MUSIC", "versio ...

Leveraging JSON Data for Avatars in React.js

Struggling to arrange 10 Avatars side by side for showcasing the user list. However, encountering an issue where the Avatars are being duplicated and showing incorrect initials when passing JSON data. Experimented with this in Code Sandbox linked below. h ...

Button failing to align properly in the center position

I was able to successfully create a responsive input box, but for some reason, the button is not aligned in the center. Below is the CSS code: .webdesigntuts-workshop button { background: linear-gradient(#333, #222); border: 1px solid #444; border- ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...

Applying Global Headers in NextJS SSR with getServerSideProps

I'm working on a project that utilizes NextJS with SSR requests using Axios within getServerSideProps. I'm curious if there is a method to intercept all Axios SSR requests and universally include the header: { "X-FOO": "BAR" ...

When is it appropriate to utilize props and CSS in customizing Material UI components?

As a beginner with Material UI, I'm curious about when to use props within the .jsx script and when to utilize CSS in a separate stylesheet to style MUI elements. Is it necessary to still incorporate CSS stylesheets for MUI elements or is it preferabl ...

Tips for customizing the background color in Material UI:

My website has a theme switcher that toggles between light and dark modes. Currently, it is set to default colors of black and white. How can I customize these colors to my own preference? View the code in SandBox Despite attempting to change the colors i ...

Optimizing Animation Effects: Tips for Improving jQuery and CSS Transitions Performance

Wouldn't it be cool to have a magic line that follows your mouse as you navigate through the header menu? Take a look at this example: It works seamlessly and smoothly. I tried implementing a similar jQuery script myself, but it's not as smoot ...

Why does the request body show as null even after passing body data in Prisma?

My application uses Prisma for database storage with MySQL. It is built using Next.js and TypeScript. I have set up the API and it is functioning properly. However, when I try to save data sent through the API, the `request.body` is null. Interestingly, wh ...

Select multiple dates using Material UI Calendar widget

Currently, I am working on incorporating the Material UI Calendar component into my project with a requirement to allow multiple date selections. The selected dates should remain highlighted even after selecting another date. Below is the current state of ...

Why does React-Perfect-Scrollbar not work properly when the height of an element is not specified in pixels?

Currently, I am developing a chat application with React 18 for its user interface. The app includes a sidebar that displays user profiles. To ensure the app fits within the browser window height, I've made the list of user profiles scrollable when n ...

Methods for applying responsive design to react modals in React.js

I am looking to make my modal responsive across different media types. In my React JS project, I have implemented custom styles using the following code: import Modal from 'react-modal'; const customStyles = { content : { top ...