I am new to react
if I close all the divs of the first button and then click second button at that time, second button divs are not opening.
Similarly if I close all the divs of the second button and then click first button div is not opening.
Can you let me know how to fix it .
even animation not working fine, all three div should open from right to left when I click on the button
Providing code below
https://stackblitz.com/edit/vitejs-vite-by5upk?file=src%2FApp.jsx,src%2FApp.css&terminal=dev
import React, { useState } from 'react';
import './App.css';
function App() {
const [currentTab, setCurrentTab] = useState(null);
const [divStates, setDivStates] = useState({
first: [false, false, false],
second: [false, false, false],
fourth: [false, false, false],
// ... Add more sets for other buttons like 'third', 'fourth'
});
const handleClick = (tabName) => {
if (currentTab === tabName) {
setCurrentTab(null);
closeAllDivs();
} else {
setCurrentTab(tabName);
setDivStates((prevStates) => ({
...prevStates,
[tabName]: prevStates[tabName].fill(true),
}));
}
};
const handleCloseDiv = (tabName, index) => {
setDivStates((prevStates) => ({
...prevStates,
[tabName]: prevStates[tabName].map((isOpen, i) =>
i === index ? false : isOpen
),
}));
if (divStates[tabName].every((isOpen) => !isOpen)) {
closeAllDivs();
}
};
const closeAllDivs = () => {
setCurrentTab(null);
setDivStates(
Object.keys(divStates).reduce(
(acc, tab) => ({
...acc,
[tab]: divStates[tab].fill(false),
}),
{}
)
);
};
return (
<div className="slide-divs-container">
<div>
<button onClick={() => handleClick('first')}>
{currentTab === 'first' ? 'Close All 1' : 'first'}
</button>
{currentTab === 'first' && (
<div className="slide-divs">
{divStates.first.map((isOpen, index) => (
<div
key={index}
className={`slide-div ${isOpen ? 'open' : 'closed'}`}
style={{ animationDelay: `${index * 100}ms` }}
>
<p>Div Content (First Group) {index + 1}</p>
<button
className="close-btn"
onClick={() => handleCloseDiv('first', index)}
>
X
</button>
</div>
))}
</div>
)}
</div>
{/* // ... other code ... */}
<div>
<button onClick={() => handleClick('second')}>
{currentTab === 'second' ? 'Close All 2' : 'Second'}
</button>
{currentTab === 'second' && (
<div className="slide-divs">
{divStates.second.map((isOpen, index) => (
<div
key={`second-group-div-${index}`} // Add a unique key
className={`slide-div ${isOpen ? 'open' : 'closed'}`}
style={{ animationDelay: `${index * 100}ms` }}
>
<p>Div Content (Second Group) {index + 1}</p>
<button
className="close-btn"
onClick={() => handleCloseDiv('second', index)}
>
X
</button>
</div>
))}
</div>
)}
</div>
{/* // ... other code ... */}
{/* ... Structures for other buttons */}
</div>
);
}
export default App;