Change maxHeight of a specific element from React

32 Views Asked by At

I'm using AntD in React and I've built an interface that displays several "Card" components representing kitchen orders.

Each card contains a div that holds the rows with order details. I would like to animate the expansion and collapse of this div when clicking the card action. Pure CSS doesn't allow perfect animation of the height property, but only maxHeight, which should be set equal to the element height to get a perfect animation. Therefore, in React, I need to obtain the scrollHeight of all the divs (i.e., the height including margins, padding, and content space).

When clicking the expand/collapse action of a specific card, I want the maxHeight of that card's div to collapse to maxHeight = 0 or expand to maxHeight = scrollHeight. Below is a piece of code that generates the cards:

const ordersDataCard = () => {
    return orders.map(order => (
        <Card size="small" key={order.key} actions={[ <Text strong className="card-action-text" onClick={() => toggleMaxHeight(order.key)} > Expand/collapse </Text>]} bordered={false} className="order-card">
            <Card.Grid className="order-info-title" hoverable={false}>Table 1</Card.Grid>
            <Card.Grid className="order-info-title" hoverable={false}>Waiting time</Card.Grid>
            <div className={ "order-items-container" }>
                <Card.Grid className="order-items" hoverable={false}>
                    {/* Kitchen order lines */}
                </Card.Grid>
                <Card.Grid className="order-items" hoverable={false}>
                    {/* Bar order lines */}
                </Card.Grid>
            </div>
        </Card>
    ));
}

When the user clicks the action button to expand/collapse, i should set the div (of that order) maxHeight like they did on js on w3schools, but in React.

if (div.style.maxHeight){ //User wants to collapse
    div.style.maxHeight = null;
} else { //User wants to expand
    div.style.maxHeight = div.scrollHeight + "px";
} 

I've seen this for getting the height, but I have multiple divs (one for each order) and the user expands and collapses any div he wants and individually.

0

There are 0 best solutions below