Home > OS >  make behavior of components independent
make behavior of components independent

Time:01-02

I am using reactJS.

I have a component AnswerButtonswhich is a group of toggle buttons like:

const [value, setValue] = useState([]);
const answers = [
    { point: 1, text: 'Answer one' },
    { point: .25, text: 'Answer two' },
    { point: .1, text: 'Answer three' },
    { point: 0, text: 'Answer four' },
]

const handleClick = (e) => { //This function simply enables toggling only one button at same time
    if (e.length === 0)
        setValue([])
    else if (e.length === 1) {
        setValue(e);
    } else {
        if (e[0] === value[0])
            setValue([e[1]])
        else
            setValue([e[0]])
    }
}

//This renders a group of 4 toggle button, 'question' is given by props
<h2>{question}</h2>
<ToggleButtonGroup type="checkbox" value={value} onChange={handleClick}>
        {answers.map((element, idx) =>
            <ToggleButton key={idx} id={idx} value={idx}>
                {element.text}
            </ToggleButton>)}
</ToggleButtonGroup>

So, I am calling that component to render a quizz :

const questions = [] //list of questions

<div>
    {questions.map((q, idx) => 
        <AnswerButtons key={idx} question={q.text}} />)}
</div>

So my problem is that whenever I toggle a button of one question, it affects only the first rendered question.

Does any body know how I can fix that please?

CodePudding user response:

the problem is the from the id.

<ToggleButton
                    size="sm"
                    key={idx}
                    variant="outline-success"
                    id={idx   question}
                    value={idx}
                  >
  • Related