Asked By: Anonymous
I created this form to generate a dynamic react page, the options are selected via the radio button.
On the current instance I’m being able to select all indicated radio buttons where i want to make this to be able to select only one radio buttons out of all generated.
<Card className={classes.root} variant="outlined">
<CardContent>
<Container component="main" maxWidth="lg">
<CssBaseline />
<Grid container spacing={3}>
<Grid item xs={6} sm={1}></Grid>
<Grid item xs={12}>
<FormLabel component="legend">{values.question.text}</FormLabel>
<FormControl component="fieldset" key={uuid()}>
<RadioGroup name="groupSingleSelect" key={uuid()}>
{values.question.items.map(item => (
<React.Fragment key={uuid()}>
<FormControlLabel
label={item.name}
value="present"
control={
<Radio
id={item.id}
name={item.name}
checked={setSelectedRadioValue(
values.question.items,
item.id
)}
onChange={props.handleSingleRadioChange(item.id)}
/>
}
/>
</React.Fragment>
))}
</RadioGroup>
</FormControl>
</Grid>
<Grid item xs={6} sm={9}>
<Button
type="submit"
variant="contained"
color="primary"
onClick={continueToNextStep}
>
Continue
</Button>
</Grid>
</Grid>
</Container>
</CardContent>
</Card>
Solution
Answered By: Anonymous
You can simply save the current selected id in a state.
const [selectedID, setID] = React.useState('');
return <Card className={classes.root} variant="outlined">
<CardContent>
<Container component="main" maxWidth="lg">
<CssBaseline />
<Grid container spacing={3}>
<Grid item xs={6} sm={1}></Grid>
<Grid item xs={12}>
<FormLabel component="legend">{values.question.text}</FormLabel>
<FormControl component="fieldset">
<RadioGroup name="groupSingleSelect">
{values.question.items.map(item => (
<FormControlLabel
label={item.name}
key={item.id}
value="present"
control={
<Radio
id={item.id}
name={item.name}
checked={item.id === selectedID}
onChange={() => {setID(item.id}}
/>
}
/>
</React.Fragment>
))}
</RadioGroup>
</FormControl>
</Grid>
<Grid item xs={6} sm={9}>
<Button
type="submit"
variant="contained"
color="primary"
onClick={continueToNextStep}
>
Continue
</Button>
</Grid>
</Grid>
</Container>
</CardContent>
</Card>
You should also just use Fragments if you wrap multiple components, which you are not doing here, so you can remove it.
Do not use uuid for keys, you already have an id for the elements, why not use these.
And keys to normal fields (not part of a list) can also be omited.