I aim to maintain the functionality of closing all ‘details’ elements when one is selected, leaving only one open at a time. However, I’m encountering challenges with the smooth transition when updating the state. I intend to soften it using CSS, but the issue arises when the state is updated; the ‘details’ element already starts open or closed, hindering the CSS transition from occurring as desired.
I’m exploring alternative solutions as saving the state of all ‘details’ doesn’t seem feasible, especially considering the list is expected to grow in the system I’m working on.
The animation doesn’t necessarily need to be done with CSS. My goal is
for the menu item to open and close. I chose to use ‘details’ for
convenience, as this functionality was already available (although I
completely overlooked this while trying to smooth the transition of
displaying the item’s content).
react
import { useState } from "react";
import Content from "./SideBar";
import './style.css'
export const SideBar = () => {
const [activeDetail, setActiveDetail] = useState("")
const toggleDetails = (index) => {
setActiveDetail(index !== activeDetail ? index : "")
}
const SideBarItem = (item) => {
return item.map((value) => {
return (
<li key={value.index} onClick={() => toggleDetails(value.index)}>
<details open={activeDetail === value.index}>
<summary> {value.name} </summary>
</details>
<div className="content">
test
</div>
</li>
);
});
};
const SideBarC = () => (
<div>
<ul className="nav flex-column">
{Content.map((value, index) => {
return <SideBarItem key={index} item={value} />;
})}
</ul>
</div>
);
return { SideBarC };
};
content
const Content = [
{
index: 1,
path: "/history",
name: "History",
},
{
index: 2,
path: "/register",
name: "Register",
}
];
css
details {
user-select: none;
overflow: hidden;
margin-bottom: .1rem;
}
.content {
overflow: hidden;
max-height: 0;
transition: max-height 0.3s ease;
padding-inline: 50px;
border-top: 0;
}
details[open] ~ .content {
transition: max-height 1s ease;
max-height: 350px;
}