Dynamic FormControlLabel Radio inside RadioGroup is not getting checked

Viewed 1338

I'm using a RadioGroup component to display a dynamic list of Radio options using FormControlLabel. The dynamic radio options are successfully getting displayed and I'm able to retrieve the selected radio option using onChange in RadioGroup. However, when I check a radio option, that particular option does not appear "checked".

Here's the code I'm using:

export default class Book extends Component {
  state = {
    slot: null,
  };
  ...
  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  };
  ...
  <FormControl component="fieldset" className={classes.formControl}>
    <FormLabel component="legend">Select availability slot</FormLabel>
    <RadioGroup
      aria-label="Slot"
      name="slot"
      className={classes.group}
      value={this.state.slot}
      onChange={this.onChange}
    >
      {this.props.experience.availability !== null ? (
        this.props.experience.availability.map(single => (
          <FormControlLabel
            key={single.id}
            value={single.id}
            control={<Radio color="primary" />}
            label={single.title}
          />
        ))
      ) : ""}
      // Some manual options in addition to the above dynamic list
      <FormControlLabel
        value="female"
        control={<Radio color="primary" />}
        label="Female"
      />
      <FormControlLabel
        value="male"
        control={<Radio color="primary" />}
        label="Male"
      />
    </RadioGroup>
  </FormControl>
  ...
}

this.props.experience.availability is an array of objects that I'm getting from a call I'm making to the backend. The call is being made in componentDidMount(). I use Redux, which makes the result available as a prop.

Now, if I manually add a few FormControlLabel components in the same RadioGroup, I can see that it's checked after selecting that option.

I've taken two screenshots - this is when the manual FormControlLabel is selected: https://ibb.co/pL5Fy6L and this is when one of my dynamic option is selected: https://ibb.co/Jq7mLN4

You can see that in the second one, the "Female" option gets unchecked but the option that I selected (20-06-2019) does not appear to be checked.

Can you please help me fix this?

Thanks in advance!

1 Answers

For anybody who might be facing the same issue, here's what I was doing wrong.

The problem was that I was passing an integer value to the value prop instead of a string like: value={single.id} so I added toString() to convert it to string like this: value={single.id.toString()} and it's working fine now.

Related