ACheckbox.tsx 2 KB
Newer Older
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
import React, { useState } from "react";
import { ICheckbox, IAnswerProps } from "../types";

export const ACheckbox = ({
  element,
  answer: answerQuestion,
}: IAnswerProps) => {
  const [content, setContent] = useState<string[]>([]);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const { value, checked } = event.currentTarget;
    // console.log("value:", value, "checked:", checked);
    if (checked) {
      content.push(value);
    } else {
      const index = content.indexOf(value);
      if (index !== -1) {
        content.splice(index, 1);
      }
    }
    // if (answerQuestion.content) {
    //   if (answerQuestion.content.find((a: any) => a === value)) {
    //     const newList = answerQuestion.content.filter((a: any) => a !== value);
    //     answerQuestion.content = newList;
    //     if (answerQuestion.content.length) {
    //       answerQuestion.requiredCheck = true;
    //     } else {
    //       answerQuestion.requiredCheck = false;
    //     }
    //   } else {
    //     answerQuestion.content.push(value);
    //     answerQuestion.requiredCheck = true;
    //   }
    // } else {
    //   answerQuestion.content = [];
    //   answerQuestion.content.push(value);
    //   answerQuestion.requiredCheck = true;
    // }
    if (content.length > 0) {
      answerQuestion.requiredCheck = true;
    } else {
      answerQuestion.requiredCheck = false;
    }
    answerQuestion.content = [...content];
    console.log("answer content", answerQuestion);
    setContent([...content]);
  };

  // console.log("content:", content);

  return (
Jiwon Yoon's avatar
Jiwon Yoon committed
52
    <div className="md:flex gap-2 justify-center my-3">
53
54
55
56
57
58
59
60
      {element.content.choices.map((choice) => (
        <div key={choice.value} className="mx-2">
          <input
            className="mr-2 w-4 h-4"
            type="checkbox"
            value={choice.text}
            onChange={handleChange}
          />
Jiwon Yoon's avatar
Jiwon Yoon committed
61
          <label className="md:text-lg text-base">{choice.text}</label>
62
63
64
65
66
        </div>
      ))}
    </div>
  );
};