Accordion.tsx 1.2 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;
7
};
Yoon, Daeki's avatar
Yoon, Daeki committed
8

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

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

19
20
  return (
    <div className="p-1">
Yoon, Daeki's avatar
Yoon, Daeki committed
21
      <div onClick={handleOpening}>
22
23
24
25
26
27
28
29
30
31
32
33
34
        <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
35
          {question.answers && getResultElementByType(question)}
36
37
38
39
40
41
42
        </div>
      </div>
    </div>
  );
};

export default Accordion;