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!!