Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of using useState hook on radio buttons

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.

like image 788
alvirbismonte Avatar asked Sep 25 '19 08:09

alvirbismonte


1 Answers

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>
like image 159
ravibagul91 Avatar answered Sep 27 '22 22:09

ravibagul91