ACheckboxForm.tsx 1.49 KB
Newer Older
Jiwon Yoon's avatar
Jiwon Yoon committed
1
import React, { useState } from "react";
2
import { CheckboxType, AnswersType, AnswerProps } from "../types";
Lee SeoYeon's avatar
Lee SeoYeon committed
3

4
interface Props extends AnswerProps {
5
  element: CheckboxType;
Jiwon Yoon's avatar
Jiwon Yoon committed
6
  answerQuestion: any | undefined;
7
}
8

Jiwon Yoon's avatar
Jiwon Yoon committed
9
export const ACheckboxForm = ({ element, answerQuestion }: Props) => {
Jiwon Yoon's avatar
Jiwon Yoon committed
10
11
12
13
  const [answer, setAnswer] = useState("");

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.currentTarget;
Jiwon Yoon's avatar
Jiwon Yoon committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    if (answerQuestion.answer) {
      if (answerQuestion.answer.find((a: any) => a === value)) {
        const newList = answerQuestion.answer.filter((a: any) => a !== value);
        answerQuestion.answer = newList;
        if (answerQuestion.answer.length) {
          answerQuestion.requiredCheck = true;
        } else {
          answerQuestion.requiredCheck = false;
        }
      } else {
        answerQuestion.answer.push(value);
        answerQuestion.requiredCheck = true;
      }
    } else {
      answerQuestion.answer = [];
      answerQuestion.answer.push(value);
      answerQuestion.requiredCheck = true;
    }
Jiwon Yoon's avatar
Jiwon Yoon committed
32
    setAnswer(value);
Jiwon Yoon's avatar
Jiwon Yoon committed
33
34

    console.log(answerQuestion);
Jiwon Yoon's avatar
Jiwon Yoon committed
35
  };
Lee SeoYeon's avatar
Lee SeoYeon committed
36
  return (
Lee SeoYeon's avatar
Lee SeoYeon committed
37
    <div className="flex w-full gap-2 justify-around my-3">
38
39
      {element.content.choices.map((choice) => (
        <div>
Jiwon Yoon's avatar
Jiwon Yoon committed
40
41
42
43
44
45
          <input
            className="mr-2"
            type="checkbox"
            value={choice.text}
            onChange={handleChange}
          />
46
          <label className="text-lg">{choice.text}</label>
Lee SeoYeon's avatar
.    
Lee SeoYeon committed
47
        </div>
48
      ))}
Lee SeoYeon's avatar
Lee SeoYeon committed
49
50
51
    </div>
  );
};