Home > database >  MUI Radio pass the label and value in onChange when selected
MUI Radio pass the label and value in onChange when selected

Time:10-29

I'm using reactjs, I have a MUI RadioGroup component from which I want to pass the label together of the selected value.

My Radio Button Code

<RadioGroup
    aria-label="am-time-in"
    value={state.AM_time_in_value}
    name="radio-buttons-group"
    onChange={onChangeRadioAMIN}
>
    {
        state.AM_timelogs_IN ?
            state.AM_timelogs_IN.map((radio) => (
                <Tooltip
                    title={
                        <>
                            <Typography variant="caption">
                                {`Scan Location: ${radio.scan_location}`}
                            </Typography>
                            <br />
                            <Typography variant="caption">
                                {`Scanned By: ${radio.scanned_by}`}
                            </Typography>
                        </>
                    }
                >
                    <FormControlLabel value={radio.time_check.split(',')[1].slice(1)} control={<Radio size="small" />} label={radio.time_standard} item={radio} />
                </Tooltip>
            )) : null
    }
</RadioGroup>

My onchange function:

const onChangeRadioAMIN = (event, value) => {   
        console.log(event);     
        event.persist();        
        setState((prev) => ({
            ...prev,
            AM_time_in_value: value,
        }));
}

CodePudding user response:

You need to create an id field to identify between your options:

const options = [
  {
    id: 0,
    scan_location: value_1,
    scanned_by: value_2,
    time_check: value_3,
    time_standard: value_4,
  },
  {
    id: 1,
    scan_location: value_1,
    scanned_by: value_2,
    time_check: value_3,
    time_standard: value_4,
  },
  ...
];

And pass the id to the value prop of FormControlLabel, the change handler will receive the id when the user changes the option. Note that you cannot pass the option object to Codesandbox Demo

  • Related