Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check radio on button click or click on radio

Using mui to create a radio button within a button and it should be possible to click on either the radio button or the button, when clicking on either of them the radio has to be checked. Only one option can be chosen, either female or male.

I know I could use multiple use states for clicked, but isn’t there some better way to do it?

import FormControl from '@mui/material/FormControl';
import FormLabel from '@mui/material/FormLabel';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Button from '@mui/material/Button';
import Radio from '@mui/material/Radio';

export const radioButtonGroup = () => {
  const [value, setValue] = React.useState('female');
  const [clicked, setClicked] = useState(false);

  return (
    <FormControl>
      <FormLabel>Gender</FormLabel>
      <RadioGroup value={value}>
        <Button
          onClick={() => setClicked(true)}
          variant="outlined">
        <FormControlLabel
          value="female"
          control={<Radio checked={clicked} />}
          label="Female" />
        </Button>
        <Button
          onClick={() => setClicked(true)}
          variant="outlined">
        <FormControlLabel
          value="male"
          control={<Radio checked={clicked} />}
          label="Male" />
        </Button>
      </RadioGroup>
    </FormControl>
  );
};

Looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

export const radioButtonGroup = () => {
  const [gender, setGender] = useState('');

  return (
    <FormControl>
      <FormLabel>Gender</FormLabel>
      <RadioGroup>
        <Button
          onClick={() => setGender('female')}
          variant="outlined">
        <FormControlLabel
          control={<Radio checked={gender === 'female'} />}
          label="Female" />
        </Button>
        <Button
          onClick={() => setGender('male')}
          variant="outlined">
        <FormControlLabel
          control={<Radio checked={gender === 'male'} />}
          label="Male" />
        </Button>
      </RadioGroup>
    </FormControl>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading