Trying to achieve expand and collapse animation on a card - ReactJS

Viewed 476

I'm trying to achieve expand and collapse animation on a card without using bootstrap or anything and for this, I tried attaching a transition property but for some reason it's not working on button click.

Here is the component: Card.jsx

import React, { useState } from 'react';
import './Card.scss';

const Card = (props) => {
    const [collapse, toggleCollapse] = useState(true);

    return (<div className="card">
        <div className="card-header">
            <h4 className="card-title">Card Actions</h4>
            <div className="heading-elements">
                <button onClick={() => toggleCollapse(!collapse)}>Collapse</button>
            </div>
        </div>
        <div className={`card-content ${!collapse ? 'collapse show' : 'collapsing'}`}>
            <div className="card-body">
                <div className="row">
                    Hi there, this content needs to shown on button click
                </div>
            </div>
        </div>
    </div>);
}

export default Card;

Here is the scss file of the card: Card.scss

.card {
    position: relative;
    display: flex;
    flex-direction: column;
    min-width: 0;
    word-wrap: break-word;
    background-color: #fff;
    background-clip: border-box;
    border-radius: 0.428rem;
    border: none;
    margin-bottom: 2rem;
    box-shadow: 0 4px 24px 0 rgba(34, 41, 47, 0.10);
    transition: all 0.3s ease-in-out, background 0s, color 0s, border-color 0s;
}

.card .card-header {
    position: relative;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-between;
    border-bottom: none;
    padding: 1.5rem;
    background-color: transparent;
}

.card-header:first-child {
    border-radius: calc(0.428rem - 1px) calc(0.428rem - 1px) 0 0;
}

.collapse:not(.show) {
    display: none;
}

.collapsing {
    position: relative;
    height: 0;
    overflow: hidden;
    transition: height 2s ease;
}
1 Answers

The problem is, when you want to collapse the card you remove the show class therefore the .collapse:not(show) selector activates where you wrote display: none;. display: none; cannot be used with a transition, take a look here for a list of properties that can be animated. Just adjusting the height should be enough.

Related