How to trigger just one accordion instead of all accordions at the same time?

Hello,

I created an accordion with multiple questions and answers, but I just want to display the answer for the question which is clicked and not all at the same time.

Can someone let me know how to just trigger the answer for the question which is clicked instead of all together?

import { useState, useEffect, useRef } from 'react';

export default function FAQ() {
  const [toggle, setToggle] = useState(false);
  const [heightEl, setHeightEl] = useState();

  const refHeight = useRef();

  useEffect(() => {
    console.log(refHeight);
    setHeightEl(`${refHeight.current.scrollHeight}px`);
  }, []);

  const toggleState = () => {
    setToggle(!toggle);
  };

  console.log(toggle);

  return (
    <div className="accordion">
      <button className="accordion-visible" onClick={toggleState}>
        <span>Question 1?</span>
        <img
          className={toggle && 'active'}
          src="./icons/plus-icon_black-margin-01.svg"
          width="20px"
        ></img>
      </button>

      <div
        className={toggle ? 'accordion-toggle animated' : 'accordion-toggle'}
        style={{ height: toggle ? `${heightEl}` : '0px' }}
        ref={refHeight}
      >
        <p aria-hidden={toggle ? 'true' : 'false'}>Answer 1</p>
      </div>

      <button className="accordion-visible" onClick={toggleState}>
        <span>Question 2?</span>
        <img
          className={toggle && 'active'}
          src="./icons/plus-icon_black-margin-01.svg"
          width="20px"
        ></img>
      </button>

      <div
        className={toggle ? 'accordion-toggle animated' : 'accordion-toggle'}
        style={{ height: toggle ? `${heightEl}` : '0px' }}
        ref={refHeight}
      >
        <p aria-hidden={toggle ? 'true' : 'false'}>Answer 2</p>
      </div>
    </div>
  );
}

Thank you for help!!

You have a single state and setstate for all of your buttons. What needs to happen is you should create a separate component, that stores its own clicked state. Render an array of that in the parent class.

1 Like

@MatchaCrisp I just solved the problem after a few hours of work by my self and then I read your answer… Yes we need to store the data in a separat component and then passing the dynamic content as props.

Thank you for your answer!! :slight_smile: