import { useState, useRef, useCallback } from "https://esm.sh/react";
import ReactDOM from "https://esm.sh/react-dom";
const collapseItems = [
{
label: "Happy day",
children: <>
<strong>I'm the children text.</strong>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. A ducimus consectetur obcaecati sunt quaerat quam odio pariatur hic molestiae repellat?</p>
</>
},
{
label: "Show content!",
children: null
},
{
label: "🥰",
children: null
}
];
function Collapse (props) {
const { index, isOpen, setIsOpenList, handleIsOpenGroup, handleParentClick, children } = props;
const handleClick = useCallback((e) => {
e.stopPropagation()
setIsOpenList(Array(collapseItems.length).fill(false));
handleIsOpenGroup(props.index, !props.isOpen);
}, [isOpen]);
const parentRef = useRef(null);
return <article class="py-2">
<button className="rounded-lg bg-amber-200 px-2 py-1 my-2 font-semibold relative z-10" onClick={handleClick}>
{props.label} <i className={ isOpen ? 'fa-solid fa-chevron-up' : 'fa-solid fa-chevron-down' }></i>
</button>
<div className="content-wrapper -translate-y-6" style={{
height: isOpen ? parentRef.current.scrollHeight + 'px' : '0px'
}} ref={parentRef}>
<div className="content border-2 border-grey-600 w-[calc(100%-12px)] sm:w-2/3 px-3 py-4 ml-2 relative">
{children || 'Default text...'}
</div>
</div>
</article>;
}
function App() {
const [isOpenList, setIsOpenList] = useState(Array(3).fill(false));
const handleIsOpenGroup = (index, isOpen) => {
setIsOpenList(prev => {
const list = [...prev];
list[index] = isOpen;
return list;
})
}
const handleParentClick = (event) => {
setIsOpenList(Array(collapseItems.length).fill(false));
}
return <>
<div class="wrapper" onClick={handleParentClick}>
{collapseItems.map((collapse, index) => <Collapse
label={collapse.label}
isOpenList={isOpenList}
isOpen={isOpenList[index]}
setIsOpenList={setIsOpenList}
handleIsOpenGroup={handleIsOpenGroup}
index={index}>
{collapse.children || 'default text...'}
</Collapse>
)}
</div>
</>;
}
ReactDOM.render(<App />, document.querySelector("#app"));
View Compiled