generated from hamadsuniverse/codecatalyst-sst-app
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathMultipleAnswersQuestionComponent.tsx
68 lines (65 loc) · 2.16 KB
/
MultipleAnswersQuestionComponent.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { QuestionMultipleAnswers } from '../../utilities/readingUtilities';
import { Answer, SetAnswer } from './QuestionsComponent';
export const MultipleAnswersQuestionComponent = ({
question,
answer,
set,
}: {
question: QuestionMultipleAnswers;
answer: Answer;
set: SetAnswer;
}) => {
const handleCheckboxChange = (subQuestionIndex: number, choice: string) => {
const newSelections = answer.map((selectedChoices, index) => {
if (index === subQuestionIndex) {
const newChoices = [...selectedChoices];
const foundIndex = newChoices.indexOf(choice);
if (foundIndex !== -1) {
// Choice is already selected, remove it
newChoices.splice(foundIndex, 1);
newChoices.push(''); // Maintain array length by adding an empty string
} else {
// Attempt to add new choice
const emptyIndex = newChoices.indexOf('');
if (emptyIndex !== -1) {
newChoices[emptyIndex] = choice; // Replace first empty slot with new choice
} else {
alert(
`You can only select up to ${selectedChoices.length} answers.`,
);
return selectedChoices; // Return old state if no room
}
}
return newChoices;
}
return selectedChoices; // Return other sub-questions' choices unmodified
});
set(newSelections as string[]);
};
console.log(answer);
return (
<div>
<p>{question.Question}</p>
<ul>
{question.SubQuestions.map((subQuestion, subIndex) => (
<li key={subIndex}>
<p>{subQuestion.QuestionText}</p>
{subQuestion.Choices.map((choice, choiceIndex) => (
<div key={choiceIndex}>
<label className="cursor-pointer">
<input
type="checkbox"
checked={answer[subIndex].includes(choice)}
onChange={() => handleCheckboxChange(subIndex, choice)}
className="mr-2"
/>
{choice}
</label>
</div>
))}
</li>
))}
</ul>
</div>
);
};