Machine code round - 1 (Accordian)

·

1 min read

accordian component in react

export const data = [
  {
    id: 1,
    question: "what is ",
    answer: "sagar",
  },
  {
    id: 2,
    question: "what is ",
    answer: "sagar",
  },
  {
    id: 3,
    question: "what is ",
    answer: "sagar",
  },
  {
    id: 4,
    question: "what is ",
    answer: "sagar",
  },
];
import "./styles.css";
import { useState } from "react";
import { data } from "./data";

export default function App() {
  const [single, setSingle] = useState(null);
  const [button, setButton] = useState(false);
  const [multi, setMulti] = useState([]);

  function handleSingle(getId) {
    setSingle(single === getId ? null : getId);
  }

  function handleButton() {
    setButton((prev) => !prev);
  }

  function handleMultiple(getId) {
    let cpyMultiple = [...multi];
    let findIndexx = cpyMultiple.indexOf(getId);
    // console.log(findIndex);
    if (findIndexx === -1) {
      cpyMultiple.push(getId);
    } else {
      cpyMultiple.splice(findIndexx, 1);
    }

    setMulti(cpyMultiple);
  }
  console.log(multi);

  return (
    <div>
      <h1>Accordian</h1>
      <div className="accordian">
        <button onClick={handleButton}>Click multiple</button>
        <div>
          {data.length &&
            data.map((item) => {
              return (
                <div
                  className="outer"
                  onClick={
                    button
                      ? () => handleMultiple(item.id)
                      : () => handleSingle(item.id)
                  }
                >
                  <p>{item.question}</p>
                  {button
                  // in multi array just print which are not -1
                    ? multi.indexOf(item.id) !== -1 && <p>{item.answer}</p>
                    : single === item.id && <p>{item.answer}</p>}
                </div>
              );
            })}
        </div>
      </div>
    </div>
  );
}

Hope you work on this and if you don't understand something you can mail me or else ask chatgpt

Thank you , God's great