Search code examples
reactjsmaterial-uiautocompleteradio-buttonaccordion

Using the label prop for FormControlLabel


I am trying to nest a RadioGroup inside AccordionDetails, then insert the Accordion list as options inside an Autocomplete component within its renderOption props.

The problem I am having is that clicking on the label (which is a span element when inspected) of the radio button closes the Autocomplete dropdown list without saving the selected value to state.

Thanks in advance!

Codesandbox: https://codesandbox.io/s/material-demo-forked-brun8?file=/demo.js


Solution

  • Use e.preventDefault() on click of the label panel

    const getLabel = ({ label, value }) => (
        <div
          value={value}
          onClick={(e) => {
            setValue(e.target.getAttribute("value"));
            e.preventDefault();
          }}
        >
          {label}
        </div>
      );
    

    Form Control Label:-

    <FormControlLabel
                  value="other"
                  control={<Radio />}
                  label={getLabel({ label: "Others", value: "other" })}
                />
    

    Codesandbox - https://codesandbox.io/s/material-demo-forked-e3hom?file=/demo.js:2650-2836