Home > Back-end >  Check radio on button click or click on radio
Check radio on button click or click on radio

Time:03-26

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:

enter image description here

CodePudding user response:

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>
  );
};
  • Related