I'm working on a react native app wherein I have created a card component that has toggleable bottom content.
This component is rendered in its parent component by mapping over a list of projects so, say, I have ten projects, ten of these cards get rendered on the screen.
I'm managing the visibility of the collapsible bottom in the Card component itself using useState
.
So, when I click on a particular card, the bottom content toggles in and out of view.
The issue I'm having is when I have clicked on a card and it's bottom content becomes visible then, when I click on another card, the first one remains open.
Basically, only one card should be open at a time.
My project structure is as follows:
Parent
- List of projects
Child ( Card )
- State for toggling visibility of bottom content
I have tried sending the index of the card that is clicked to the parent as follows:
In child component:
useEffect(() => {
setCardState( prev => !prev );
}, [props.isActive]);
const [cardOpen, setCardState] = useState(true);
<TouchableOpacity
onPress={() => {
props.onClick( props.cardIndex );
}}>
( visible upper part )
</TouchableOpacity>
{cardOpen && (
(Bottom collapsible content)
)}
.
.
.
And in parent:
{projects.map((project, index) => {
return (
<ProjectCard
cardIndex={index}
isActive={activeIndex == index}
key={index}
onClick={(clickedIndex) => toggleCardState(clickedIndex)}
project={project}
/>
);
})}
function toggleCardState(index) {
let tempFlags = [...cardFlags];
tempFlags[activeIndex] = false;
setActiveIndex(() => index);
setCardFlags([...tempFlags]);
// console.log('activeIndex', activeIndex);
// console.log('cardflags', cardFlags);
}
Since the way ReactNative works, the states aren't updated properly. How can I achieve the desired functionality or is there any other( better ) way to do that?
Expected Behaviour:
- Click on card a
- Card a gets opened
- Click on card b
- Card a closes and card b opens
Actual Behaviour:
- Click on card a
- Card a opens
- Click on card b
- Card a closes and card b opens
- Click again on card b
- Card b stays open
I'm using RN 0.63
question from:
https://stackoverflow.com/questions/65843237/toggle-visibility-of-a-card-component-and-close-the-open-card-while-opening-anot 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…