Skip to content

Commit 1eeb46c

Browse files
committed
feat: add multiple choice questions
1 parent c84c379 commit 1eeb46c

File tree

2 files changed

+45
-12
lines changed

2 files changed

+45
-12
lines changed

components/mdx/Question.tsx

Lines changed: 29 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Box, VStack, Text, Button, useToast } from '@chakra-ui/react'
2-
import React, { FC, useState } from 'react'
2+
import React, { FC, useState, Dispatch, SetStateAction } from 'react'
33

44
interface QuestionProps {
55
question: string
@@ -17,19 +17,26 @@ interface Question {
1717

1818
const Question: FC<QuestionProps> = (props: QuestionProps) => {
1919
const question: Question = require(`../../utils/questions/${props.question}.json`)
20-
const [optionSelected, setOptionSelected]: [
21-
number,
22-
React.Dispatch<React.SetStateAction<number>>,
23-
] = useState(-1)
24-
const [answersSubmitted, setAnswersSubmitted] = useState(false)
20+
const [optionsSelected, setOptionsSelected]: [
21+
number[],
22+
Dispatch<SetStateAction<number[]>>,
23+
] = useState([-1])
2524
const toast = useToast()
2625

2726
const selectAnswer = (optionIndex: number) => {
28-
setOptionSelected(optionIndex)
27+
if (optionsSelected.indexOf(optionIndex) !== -1) {
28+
return setOptionsSelected(
29+
optionsSelected.filter((o) => o !== optionIndex),
30+
)
31+
}
32+
33+
setOptionsSelected(
34+
[...optionsSelected, optionIndex].filter((o) => o !== -1), // Remove the -1 of the state initialization
35+
)
2936
}
3037

3138
const getOptionBackground = (optionIndex: number) => {
32-
if (optionSelected == optionIndex) {
39+
if (optionsSelected.indexOf(optionIndex) !== -1) {
3340
return 'yellow.600'
3441
}
3542
return 'gray.600'
@@ -66,13 +73,23 @@ const Question: FC<QuestionProps> = (props: QuestionProps) => {
6673
}
6774

6875
const submit = () => {
69-
if (optionSelected === -1) {
76+
if (optionsSelected.indexOf(-1) !== -1) {
7077
return quizNotAnswered()
7178
}
7279

73-
if (question.options[optionSelected].correct) {
74-
return quizSuccessToast()
75-
}
80+
const correctAnswers = question.options.filter((o) => o.correct).length
81+
82+
let success = true
83+
let correctAnswersCount = 0
84+
85+
optionsSelected.forEach((o) => {
86+
if (!question.options[o].correct) success = false
87+
correctAnswersCount++
88+
})
89+
90+
if (correctAnswers !== correctAnswersCount) success = false
91+
92+
if (success) return quizSuccessToast()
7693

7794
return quizFailedToast()
7895
}

utils/questions/question-2.json

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"question": "Which of these properties does Ethereum have?",
3+
"options": [
4+
{
5+
"answer": "Permissioned"
6+
},
7+
{
8+
"answer": "Trustless",
9+
"correct": true
10+
},
11+
{
12+
"answer": "Decentralized",
13+
"correct": true
14+
}
15+
]
16+
}

0 commit comments

Comments
 (0)