Jc John
Jc John

Reputation: 1859

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,
})

Upvotes: 0

Views: 5125

Answers (1)

Viet
Viet

Reputation: 12807

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

Just update defaultValue to value

value={state.privateEntity}

Upvotes: 5

Related Questions