Accordion.tsx 1.23 KB
Newer Older
1
import React, { useState, useRef, useEffect } from "react";
Yoon, Daeki's avatar
Yoon, Daeki committed
2
import { IQuestionData } from "../types";
3
import { getResultElementByType } from "../helpers/question.helper";
Yoon, Daeki's avatar
Yoon, Daeki committed
4

5
type AccordionProps = {
Yoon, Daeki's avatar
Yoon, Daeki committed
6
  question: IQuestionData;
Jiwon Yoon's avatar
Jiwon Yoon committed
7
  answers: any;
8
};
Yoon, Daeki's avatar
Yoon, Daeki committed
9

Jiwon Yoon's avatar
Jiwon Yoon committed
10
export const Accordion = ({ question, answers }: AccordionProps) => {
11
12
13
14
  const [isOpened, setOpened] = useState<boolean>(false);
  const [height, setHeight] = useState<string>("0px");
  const contentElement = useRef<HTMLDivElement>(null);

Yoon, Daeki's avatar
Yoon, Daeki committed
15
  const handleOpening = () => {
16
17
18
    setOpened(!isOpened);
    setHeight(!isOpened ? `${contentElement.current?.scrollHeight}px` : "0px");
  };
Yoon, Daeki's avatar
Yoon, Daeki committed
19

20
21
  return (
    <div className="p-1">
Yoon, Daeki's avatar
Yoon, Daeki committed
22
      <div onClick={handleOpening}>
23
24
25
26
27
28
29
30
31
32
33
34
35
        <div
          className={
            "bg-themeColor rounded-r-lg p-4 flex justify-between text-white"
          }
        >
          <h4 className="font-semibold">{question.title}</h4>
          {isOpened ? "" : ""}
        </div>
        <div
          ref={contentElement}
          style={{ height: height }}
          className="bg-gray-100 overflow-hidden transition-all duration-300"
        >
Jiwon Yoon's avatar
Jiwon Yoon committed
36
          {answers && getResultElementByType(question, answers)}
37
38
39
40
41
42
43
        </div>
      </div>
    </div>
  );
};

export default Accordion;