Skip to content

Commit

Permalink
Refactor into separate component ChoiceForm
Browse files Browse the repository at this point in the history
  • Loading branch information
leung018 committed Apr 9, 2024
1 parent ec084dd commit 9b15e7c
Showing 1 changed file with 54 additions and 31 deletions.
85 changes: 54 additions & 31 deletions src/app/components/quiz.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,39 +168,62 @@ function QuestionForm({
<p className="font-bold whitespace-pre-line">{question.description}</p>
<div className="ml-4">
{question.mc.choices.map((choice, choiceIndex) => (
<span key={choiceIndex}>
<label className="flex items-center mb-2">
<input
type="radio"
className="mr-2"
checked={choiceIndex === checkedChoiceIndex}
onChange={() => handleChoiceChange(choiceIndex)}
disabled={isSubmitted}
/>
{choice.answer}
</label>
{isSubmitted && checkedChoiceIndex === choiceIndex && (
<span className="ml-2">
{question.mc.correctChoiceIndex === choiceIndex ? (
<span
className="text-green-500"
aria-label={`${choice.answer} is correct`}
>
</span>
) : (
<span
className="text-red-500"
aria-label={`${choice.answer} is wrong`}
>
</span>
)}
</span>
)}
</span>
<ChoiceForm
key={choiceIndex}
answer={choice.answer}
onSelect={() => handleChoiceChange(choiceIndex)}
isChecked={checkedChoiceIndex === choiceIndex}
isSubmitted={isSubmitted}
isCorrectAnswer={question.mc.correctChoiceIndex === choiceIndex}
/>
))}
</div>
</div>
)
}

function ChoiceForm({
answer,
onSelect,
isChecked,
isSubmitted,
isCorrectAnswer,
}: {
answer: string
onSelect: () => void
isChecked: boolean
isSubmitted: boolean
isCorrectAnswer: boolean
}) {
return (
<span>
<label className="flex items-center mb-2">
<input
type="radio"
className="mr-2"
checked={isChecked}
onChange={() => onSelect()}
disabled={isSubmitted}
/>
{answer}
</label>

{isSubmitted && isChecked && (
<span className="ml-2">
{isCorrectAnswer ? (
<span
className="text-green-500"
aria-label={`${answer} is correct`}
>
</span>
) : (
<span className="text-red-500" aria-label={`${answer} is wrong`}>
</span>
)}
</span>
)}
</span>
)
}

0 comments on commit 9b15e7c

Please sign in to comment.