Correct way of using useState hook on radio buttons
Asked Answered
A

3

11

I followed the ReactJS documentation regarding the useState hook but I cannot get it to work with radio buttons. It doesn't select any radio button at all. By the way I am using react-semantic ui for the component.

The radio buttons should select the gender assigned to the state. I've tried to console.log the gender variable and it changes but does not reflect on the ui.

Here's my code for your reference.

import React, { useState } from 'react';

const ListCreateNew = () => {
  const [gender, setGender] = useState('Male');
  return (
      <Form.Group inline>
        <label>Gender</label>
        <Form.Field control={Radio} label="Male" checked={gender === 'Male'} value="Male" onClick={() => setGender('Male')} />
        <Form.Field control={Radio} label="Female" checked={gender === 'Female'} value="Female" onClick={() => setGender('Female')} />
      </Form.Group>
  );
}

EDIT: I apologize everyone. I've missed the anonymous function on the onClick attrib.

Arlinearlington answered 25/9, 2019 at 8:39 Comment(1)
Your code is working codesandbox.io/s/romantic-galois-nb4e5Fidelfidela
S
15

You should use annonymous function to update the state,

<Form.Field control={Radio} label="Male" checked={gender === 'Male'} value="Male" onClick={() => setGender('Male')} />
<Form.Field control={Radio} label="Female" checked={gender === 'Female'} value="Female" onClick={() => setGender('Female')} />

Update

For the radio button, you have Form.Radio

<Form.Group inline>
    <label>Gender</label>
    <Form.Radio label="Male" checked={gender === 'Male'} value="Male" onClick={() => setGender('Male')} />
    <Form.Radio label="Female" checked={gender === 'Female'} value="Female" onClick={() => setGender('Female')} />
</Form.Group>
Selfsealing answered 25/9, 2019 at 8:43 Comment(5)
Hi, I added an edit regarding the anonymous function. I actually have that already on my code but it still doesn't work.Arlinearlington
You are setting it wrong here checked={() => gender === 'Female'} it should be ``checked={gender === 'Female'}. Your annonymous function is only on onClick jandler.Selfsealing
Hi, sorry, getting too much typo error. Updated it again.Arlinearlington
@alvirbismonte, check the updated answer, you are referring to the wrong element type for your radio.Selfsealing
react.semantic-ui.com/collections/form/#shorthand-field-controlFidelfidela
C
3
const [radio,setRadio] = useState('false')

<Form>

<Form.Check inline label="Response A" type="radio" id="radioA" value="radioA" checked={radio === "radioA"} onChange={(e)=>{setRadio(e.target.value)}}/>

<Form.Check inline label="Response B" type="radio" id="radioB" value="radioB" checked={radio === "radioB"} onChange={(e)=>{setRadio(e.target.value)}}/>
                                
<Form.Check inline label="Response C" type="radio" id="radioC" value="radioC" checked={radio === "radioC"} onChange={(e)=>{setRadio(e.target.value)}}/>
                                
<Form.Check inline label="Response D" type="radio" id="radioD" value="radioD" checked={radio === "radioD"} onChange={(e)=>{setRadio(e.target.value)}}/>
                            
</Form>
Contagion answered 5/1, 2022 at 7:16 Comment(1)
It would be helpful if you could add a bit of explanation/comments on why/how your code works!Fishmonger
B
0

Below code should Help

        const [userData, setUserData] = useState({
        sex: "",
        });

        <div className="flex justify-around">
          <div className="flex items-center mb-4 justify-left">
            <input
              id="country-option-2"
              type="radio"
              name="sex"
              value="male"
              onClick={(e) =>
                setUserData({ ...userData, sex: e.target.value })
              }
              className="w-4 h-4 border-gray-300 focus:ring-2 focus:ring-blue-300 dark:focus:ring-blue-600 dark:focus:bg-blue-600 dark:bg-gray-700 dark:border-gray-600"
            />
            <label
              for="country-option-2"
              className="block ml-2 text-sm font-medium text-gray-900 dark:text-gray-300"
            >
              Male
            </label>
          </div>
          <div className="flex items-center mb-4 justify-left">
            <input
              id="country-option-2"
              type="radio"
              name="sex"
              value="female"
              onClick={(e) =>
                setUserData({ ...userData, sex: e.target.value })
              }
              className="w-4 h-4 border-gray-300 focus:ring-2 focus:ring-blue-300 dark:focus:ring-blue-600 dark:focus:bg-blue-600 dark:bg-gray-700 dark:border-gray-600"
            />
            <label
              for="country-option-2"
              className="block ml-2 text-sm font-medium text-gray-900 dark:text-gray-300"
            >
              Female
            </label>
          </div>
        </div>
Bogan answered 27/9, 2023 at 21:43 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Mitra

© 2022 - 2024 — McMap. All rights reserved.