I'm trying to render some questions to evaluate the old device price. From backend I'm receiving multiple questions and I have to give a radio button to the question for YES/NO to for the selection, But when I click One radio button other buttons also get clicked. How to fix this.
My code.
const [radioValue, setRadioValue] = useState('0')
const radios = [
{ name: 'Yes', value: '1' },
{ name: 'No', value: '0' }
And this is the rendering part:
{specialQuestLoading ? (
<Loader></Loader>
) : specialQuestError ? (
<Message color="danger"> {specialQuestError} </Message>
) : (
<>
{specialQuestions ? (
specialQuestions.map((question) => (
<Card classNames="mx-2 py-2" key={question.id}>
{question.question_brand === order.prod_brand ? (
<>
<Card.Title> {question.question}</Card.Title>
<Row>
{' '}
<Col md={4}> </Col>
<ButtonGroup className="mb-2">
{radios.map((radio, idx) => (
<ToggleButton
key={idx}
id={`radio-${idx}`}
type="radio"
variant="secondary"
name="radio"
value={radio.value}
checked={radioValue === radio.value}
onChange={(e) => setRadioValue(e.currentTarget.value)}
>
{radio.name}
</ToggleButton>
))}
</ButtonGroup>
<>
<br />
</>
</Row>
</>
) : (
<></>
)}
</Card>
))
) : (
<></>
)}
</>
)}
And this is the problem. Both get checked clicking the one. Any body knows how to fix this, Or How can I fix this ?
CodePudding user response:
You are using single state for every specialQuestions
Card. So changing any of the ToggleButton
affects every Card
Element (specialQuestions).
You should split the Card
Element to a separate Component and manage the radioValue
state there.
export const Card = ({question}) => {
const [radioValue, setRadioValue] = useState('0')
const radios = [
{ name: 'Yes', value: '1' },
{ name: 'No', value: '0' }
return (
<Card classNames = "mx-2 py-2" key = {question.id} >
{question.question_brand === order.prod_brand ? (
<>
<Card.Title >
{question.question}
</Card.Title>
<Row>
{' '}
<Col md = {4}>< /Col>
<ButtonGroup className = "mb-2" >
{radios.map((radio, idx) => (
<ToggleButton
key = {idx}
id = {`radio-${idx}`}
type = "radio"
variant = "secondary"
name = "radio"
value = {radio.value}
checked = {radioValue === radio.value}
onChange = {
(e) => setRadioValue(e.currentTarget.value)
}
>
{radio.name}
</ToggleButton>
))
}
</ButtonGroup>
<><br /></>
</Row>
</>)
: ( <></>)
}
</Card>
)
}
And consume it as
specialQuestions.map((question) => (
<Card question={question} />
)