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

4
interface Props extends AnswerProps {
5
  element: CheckboxType;
6
}
7

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

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = event.currentTarget;
Jiwon Yoon's avatar
Jiwon Yoon committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    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
31
    setAnswer(value);
Jiwon Yoon's avatar
Jiwon Yoon committed
32
33

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