I have a question regarding creating expanding flex cards. I found an example on Codepen that showcases what I'd like to achieve: https://codepen.io/z-/pen/OBPJKK
In my code, I have a component called HomeButtons that generates these flex cards. Within this component, there is a smaller component named ReadMore. Inside ReadMore, I have a useState hook that allows me to toggle each button individually by adding or removing an active class. When the active class is present, the selected button expands while the others shrink.
My goal is to access the state of ReadMore outside of its subcomponent so that I can write a function to remove the active class from a card when another is clicked:
function setToInactive() {
if (readMore(true)) {
readMore(false)
}
}
How can I retrieve the state of ReadMore outside of the subcomponent? Do I need to utilize useContext? I've tried various approaches without success. Is it possible to pass the ReadMore state as a prop to the ReadMore component instead? Thank you!
import React, { useState } from 'react';
import '../style/catalogue.scss';
import collectionsItems from '../Components/collectionsItemsData';
import { Link } from "react-router-dom";
const HomeButtons = ({}) => {
function ReadMore() {
const [readMore, setReadMore] = useState(false);
function toggleSetReadMore() {
setReadMore(!readMore);
}
return (
<p className='showmore' onClick={toggleSetReadMore} className={readMore ? "collection-item active" : "collection-item"}>TOGGLE BUTTON</p>
)
}
return (
<div>
{collectionsItems.map((collectionItem) => {
const { id, category, img } = collectionItem;
return (
<article key={id}>
<img className="item-img" src={img} alt=''/>
<ReadMore />
<Link to={`/${category}`} className="item-title">{category}</Link>
</article>
)
})}
</div>
);
}
export default HomeButtons;