skip to Main Content

I use a state to render different components in a div hence changing its height. I want my css height transition to execute when the change happens. Please someone assist me with this.

React Code:

<div className="venue-details">
            {venue ? 
                <>
                    <span>Date: &nbsp;To Be Announced... </span><br />
                    <span>Location: &nbsp; My Location</span><br />
                </>:
                <>
                    <span>Click to view</span>
                </>
            }
</div>

CSS Code:

.venue-details{
    position: relative;
    font-size: 20px;
    padding-left: 10%;
    padding-bottom: 30px;
    padding-right: 10%;
    transition: height 1s ease-in-out;
}

2

Answers


  1. The problem is that you’re adding/removing your spans to/from the dom, not changing the classes on them. Try something more like this:

    <div className={venueDisplayClass} >
       <p className="withVenue">
            Date: TBA
       </p>
       <p className="withVenue">Location: TBA</p>
       <button className="withoutVenue" onClick={setVenueDisplayClass('showVenue')}>Click to View</button>
    </div>
    

    And then your css can be more like

    .showVenue .withVenue {
       height: auto;
       transition: /* your transition */
    }
    .showVenue .withoutVenue {
      height: 0;
      transition: /* your transition */
    }
    
    .hideVenue .withVenue {
       height: 0;
    }
    
    .hideVenue .withoutVenue {
       height: auto;
    }
    
    Login or Signup to reply.
  2. You could use ReactTransitionGroup to animate the height of your div element:

    import { CSSTransition } from 'react-transition-group';
        // ...
        
        <CSSTransition
          in={venue}
          timeout={1000}
          classNames="venue-details"
        >
          <div className="venue-details">
            {venue ? (
              <>
                <span>Date: &nbsp;To Be Announced... </span><br />
                <span>Location: &nbsp; My Location</span><br />
              </>
            ) : (
              <>
                <span>Click to view</span>
              </>
            )}
          </div>
        </CSSTransition>
    

    css:

    .venue-details-enter {
      height: 0;
    }
    
    .venue-details-enter-active {
      height: [desired-height];
      transition: height 1s ease-in-out;
    }
    
    .venue-details-exit {
      height: [desired-height];
    }
    
    .venue-details-exit-active {
      height: 0;
      transition: height 1s ease-in-out;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search