Clicking on a radio button will automatically unselect any other radio button in the group

Hey there, I'm facing an issue while trying to create a radio button group. When I choose an option in one group, it automatically deselects the options in the other group.

Here's the code snippet:

<>
      <div className="orientation_mode">
        <h1>Dashboard Orientation</h1>
        <div className="options">
          <form>
            <fieldset id="orientation_mode">
              <RadioButton
                onChange={handleInputChange}
                id="vertical"
                color="#c8c8c8"
                name="orientation_mode"
                label="Vertical"
                value="vertical"
                checked={layoutStore.layoutType === 'vertical'}
              />
              <RadioButton
                id="horizontal"
                color="#c8c8c8"
                name="orientation_mode"
                onChange={handleInputChange}
                label="Horizontal"
                value="horizontal"
                checked={layoutStore.layoutType === 'horizontal'}
              />
            </fieldset>
          </form>
        </div>
      </div>
      <div className="theme_modes">
        <h1>Theme Mode</h1>
        <div className="options">
          <form>
            <fieldset id="theme_modes">
              <RadioButton
                id="dark"
                name="theme_modes"
                onChange={handleInputChange}
                label="Dark"
                value="dark"
              />
              <RadioButton
                id="semidark"
                name="theme_modes"
                onChange={handleInputChange}
                label="Semi Dark"
                value="semidark"
              />
              <RadioButton
                id="light"
                name="theme_modes"
                onChange={handleInputChange}
                label="Light"
                value="light"
              />
            </fieldset>
          </form>
        </div>
</>

In case you need the complete code, visit this codesandbox link: https://codesandbox.io/s/recursing-shockley-9jvey?file=/src/RadioButton.tsx

You can also check out the animation demonstration here: https://i.sstatic.net/NypZb.gif

Answer №1

Revise your CSS by replacing focus with checked:

&:checked + .radio__control { // include styles here }

Incorporate additional properties into your radioButton's input, such as type=radio:

<input type="radio" className="radio" id={id} name={name} value={value} onChange={onChange} checked={checked} />

Redefine the type for the onChange function:

onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;

Add state to App to manage theme and orientation:

  const [theme, setTheme] = useState('light');
  const [orientation, SetOrientation] = useState('horizontal');
  const handleTheme = (e: React.ChangeEvent<HTMLInputElement>) => setTheme(e.target.value)
  const handleOrientation = (e: React.ChangeEvent<HTMLInputElement>) => SetOrientation(e.target.value)

Pass the onChange and checked properties like this:

        <RadioButton
          id="dark"
          name="theme_modes"
          onChange={handleTheme}
          label="Dark"
          value="dark"
          checked={ theme === 'dark' } // alternatively, pass theme and validate within RadioButton
        />

Here's a working example: https://codesandbox.io/s/quirky-cookies-1nru9?file=/src/App.tsx

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

Determining If Props Have Been Undefined In React

Greetings and thank you for taking the time to read this: I am currently working through a tutorial that can be found here: My issue lies in the creation of an author, where the application is trying to load the URL of the current author's ID, which ...

CSS Text-Align failing to align elements

As a newcomer to CSS, I am seeking assistance with aligning items on a webpage. Essentially, I am trying to achieve an alignment that resembles the following: Item 1 ...

Hide multiple divs with similar ids in JQuery when clicking outside of them

Is there a way to hide all div elements with similar id if none of them are clicked on? Currently, my code only works for the first div because I am using index[0] to retrieve the id. How can I make it work for all ids? Below is the code snippet: $(win ...

Eliminate the alert message that appears when dynamically rendering a React styled component

When checking the browser console, I noticed a warning that reads as follows: react_devtools_backend.js:3973 The component styled.div with the id of "sc-dmRaPn" has been created dynamically. You may see this warning because you've called sty ...

React Component content is failing to display or cannot be located

As a newcomer to building frontends with React, I recently added routes to my project. However, since then, the pages are not rendering correctly and I'm struggling to identify the source of the error. Here is what happens when I visit the homepage p ...

What is the best way to connect an HTML image to effortlessly switch between displaying and hiding an element (specifically, a table) using JavaScript?

Apologies if my question is a bit confusing and poorly written, as I am new to coding and Stack Overflow. What I am trying to achieve is the ability to click on each image and have a different table pop up for each planet with facts (an example of the Merc ...

Enhanced method for submitting files along with accompanying data

Currently, I am in the process of developing an application using React for the frontend and Nodejs for the backend. To handle file storage, I am utilizing multer along with minIO. At the moment, the application includes a form where users can input data ...

I am having trouble with retrieving and showing Json data in a table using axios within a React component

Struggling to access JSON data using hooks to display it in the <p> tag but encountering an error - "TypeError: states.map is not a function". I attempted utilizing Array.from() to convert my JSON to an array, yet it neither displayed anything nor pr ...

Error: The function addProductPaymentResponse() is missing the mandatory argument 'paymentForOrderID'

In order to limit post requests, I need to check if a similar str(number) in the paymentForOrderID already exists in the ProductPayment model. #model.py class ProductPayment(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, nul ...

Experiencing an issue with hasClass when conducting jest testing on react components

I've recently started using Jest to test my React components, and this is my very first test. Here's the code snippet for my component: import React from 'react'; import PropTypes from 'prop-types'; import uuidv1 from 'u ...

Just starting out with Flexbox - what steps should I take?

In the code, there are three divs arranged in the DOM by div-00#. I am seeking to achieve the following layout using flexbox (for width >= 460px) as shown in the images below: https://i.sstatic.net/I2PFQ.png Added: 18-12-16 - https://i.sstatic.net/v ...

The agreement does not involve an NFT release on the third web platform

Attempting to integrate my contracts into my upcoming application through thirdweb has hit a roadblock. I keep encountering the following error: "Error: Contract is not a nft-drop". Even after trying to troubleshoot by copying and pasting the exact code fr ...

When utilizing Material-UI Dialog or Modal and clicking on a TextField, the field loses focus each time an onChange

<List key={"test1"} style={{ marginBottom: '10px' }}> <TextField required id="filled-basic" key={categoryData.title} label="Title" ...

The functionality of Bootstrap v4 push and pull grid classes seems to be failing to meet expectations

In the process of developing a web application, I am using Bootstrap v4 (alpha 3) to create a responsive layout. Most elements are working well, however, I am facing difficulties rearranging my cards using the push and pull classes in Bootstrap. The intend ...

#React How to include an image within a component

Currently, I am attempting to define my "Logo" as an image. I attempted to create a logo.js component, defining it as an image and calling it here, but I am at a loss on how to solve this issue. Below is my banner component, import React from 're ...

Is the Express server double-posting, with a two-minute gap between each post?

I'm currently working on a project involving the development of a React chat box with an express server and pusher for dialogflow bot integration. Initially, everything seems to be running smoothly, but I'm encountering an issue where the bot res ...

When resizing an anchor tag with a percentage in CSS, the child image width may not scale accordingly

In short, I have multiple draggable images on a map enclosed in anchor tags (<a><img></a>) to enable keyboard dragging. The original image sizes vary, but they are all too large, so I reduced them to 20% of their original sizes using the ...

What is the best way to prevent the content within a div from being obscured by a sticky element affixed to the bottom of the div?

I am struggling with ensuring that the content in my wrapper does not get cut off by the "view more" div attached to the bottom. The default wrapper cuts off the children, and even when expanded, the issue persists due to CSS problems. In React, the gener ...

Footer displaying incorrectly

My webpage has a white footer set at 30px in height. However, when I scroll down the page, the footer expands and overlaps with the text part (a div with a light grey background). Can you help me figure out what's causing this issue and how to fix it? ...

Aligning items vertically within a container with a constant height

I'm currently working on a website that requires a pixel-based navbar with a height of 80px. The issue I'm facing is the difficulty in vertically centering the ul and li elements. I have experimented with various methods such as using top:50%; ...