简体   繁体   中英

Reactjs Uncontrolled component error in material ui radio button group

I am beginner in using ReactJS. I have an error regarding my component radio button group from material UI. I have a radio button that has a value of boolean.

When I tried to click a value in my radio button, it doesn't select but the console log from onchange function was fired and an error will display like this: Material-UI: A component is changing the default value state of an uncontrolled RadioGroup after being initialized. To suppress this warning opt to use a controlled RadioGroup.

Here is my full code:

<Grid item>                        
    <RadioGroup row aria-label="privateEntity" name="privateEntity" defaultValue={state.privateEntity} onChange={changePrivateEntity}>
        <FormControlLabel value={true} disabled={requestType === 'PUT' || state.agency} control={<Radio color="primary" />} label="YES" />
        <FormControlLabel value={false} disabled={requestType === 'PUT' || state.agency} control={<Radio color="primary" />} label="NO" />
    </RadioGroup>
</Grid>

Here is my onchange function:

const changePrivateEntity = (event, value) => {
    event.persist();
    // console.log(value);
    let x = value === 'true' ? true : false;    
    setState((prev) => ({
      ...prev,
      privateEntityDefined: true,
      privateEntity: x,
      inputErrors: {
        ...prev.inputErrors,
        privateEntity: false,
      },
      inputHelpTexts: {
        ...prev.inputHelpTexts,
        privateEntity: '',
      },
    }));
  };

Here is my state initialization:

const [state, setState] = useState({
    privateEntity: selectedRecord ? selectedRecord.agency.private_entity : null,
    privateEntityDefined: !!selectedRecord,
})

Because you don't pass value for RadioGroup component so it'll show this warning:

Just update defaultValue to value

value={state.privateEntity}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM