Implement transition effect on collapsible div with styled-components in React

I am attempting to develop a straightforward collapsible div using styled-components within a react project.

While I have successfully managed to toggle the div's open and close state based on certain conditions, I am facing difficulties in implementing a smooth transition effect. Currently, it abruptly switches between open and closed states without any animation.

Below is the code for the Styled Component:

const Details = styled.div`
    transition: 0.3s ease-out;

    &.open {
        height: auto;
        padding: 25px 0;
    }

    &.closed {
        height: 0;
        overflow: hidden;
    }
`;

And here is the JSX code snippet:

<Details className={this.state.detailsOpen ? 'open' : 'closed'}>
    {stuff}
</Details>                

Answer №1

If you want to trigger the animation, it's recommended to use max-height as mentioned in the comments. Instead of relying on className while using styled-components, consider passing the state as a prop directly to the component:

JSX

<Details open={this.state.detailsOpen}>
    {stuff}
</Details> 

Styled Component

const Details = styled.div`
    max-height: ${props => props.open ? "100%" : "0"};
    overflow: hidden;
    padding: ${props => props.open ? "25px 0" : "0"};
    transition: all 0.3s ease-out;
`;

An example demonstrating this can be found on code sandbox: https://codesandbox.io/s/1qrw632214

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for utilizing navigator.getDisplayMedia with automatic screen selection:

navigator.mediaDevices.getDisplayMedia({ audio: false, video: true }).then(gotMedia).catch(function(e) { console.log('getDisplayMedia() error: ', e); }); Triggering the above code will result in a popup like this. There is anoth ...

Altering the slider marks' text color in React with MUI 5

Having recently delved into MUI 5, I'm facing a challenge in accessing the marks property of the slider to customize its color. Below is my slider code: <Slider color="secondary" defaultValue={c ...

Chip component in Material UI for Meteor/React not recognizing the onRequestDelete method

I'm currently integrating Material UI's chip element into my application and as per the documentation onRequestDelete - Callback function triggered when the delete icon is clicked. If specified, the delete icon will be displayed. import React f ...

tips for patiently awaiting an ajax response before setting the object

I am currently working on a basic todo app using React. Initially, everything was running smoothly when I stored my data in a pre-defined object. However, now that I am retrieving my data from a link (rest) using AJAX, I seem to be encountering some issues ...

Error encountered when attempting to trigger a Bootstrap dropdown within a designated div

When using React JS, I encountered an issue when trying to trigger a dropdown that was nested inside a div with the class name "row". Initially, I placed the data-toggle and data-target attributes inside the div, like so: <div className="row"> < ...

What is the best way to adjust the hue of an image?

Apologies for the lack of clarity in the title, I'm unsure of how to articulate my question accurately so I'll try to explain my idea instead. I am working on developing an app that allows users to customize the colors of various parts of a car. ...

An unexpected error occurred in Nextjs 13: an Uncaught (in promise) SyntaxError was thrown due to an unexpected token "'<'" in the JSON data, making it invalid

At the moment, I am attempting to retrieve a response from my server component in Next.js 13. Here is the snippet of code I am working with: import db from "../../../../utils/db"; import Product from "../../../../models/Product"; import { NextResponse } ...

A step-by-step guide on activating ListItemButton with React Router v6 Link

Seeking guidance on integrating the functionality of MUI's Mini Variant Drawer example with React Router v6's Link element. The documentation lacks clarity on this aspect, and my attempts to configure it have been unsuccessful despite multiple it ...

The requirement for the type 'Promise<QuerySnapshot<DocumentData>>' is that it must include a method '[Symbol.iterator]()' to provide an iterator

Currently, I am developing a Firebase project with NextJS and Typescript. My goal is to retrieve data from the Firestore database; however, I encountered an error message stating Type 'Promise<QuerySnapshot<DocumentData>>' must have a ...

Pressing a button triggers the highlighting of a tab in HTML through the use of Javascript

In the corner of my webpage, I have three tabs: info, question, order. When I click on one tab header, only that tab should highlight. The info section includes two buttons that link to the question and order tabs. When these buttons are pressed, the respe ...

Add distinctive formatting for the final element that is not the last child

Presented with a fascinating challenge, I find myself with an ever-changing number of .child.red children. I am in need of referencing the last .child.red element dynamically using styles. Although I have attempted to achieve this on my own, I am curious a ...

javascript issue with setting the id attribute on a select option

I can't seem to set the id attribute in my select element using JavaScript. When I inspect it, the id attribute isn't showing up... Here's the first method using JS: var selectorElem = document.getElementById('selector') var ...

Design a Unique CSS Shape

Do you have any suggestions on how to create this shape using only CSS, without SVG paths? Thank you in advance! Check out the screenshot here ...

Is there a way to point the Facebook crawler bot to a different page?

I have a small website built with PreactJS that includes some parts from the main website (PHP). Since Facebook bot cannot crawl pre-rendered JavaScript content when shared, I want to redirect it to crawl the main PHP website instead when a link to the Pre ...

Exemplary CSS Text Alignment When Vertical Align is Exceptional

I'm currently working on a menu where some text needs to be aligned vertically with the property vertical-align:super. However, I am facing an issue where this particular item with "super" text is not aligning properly with the other items. Below is ...

Utilizing external CSS to style an SVG file within an HTML document

Hello there, I have a collection of SVG files that I need to dynamically modify the fill color of, preferably using CSS. Here is the structure: <div> <svg width="100%" height="100%" viewbox="0 0 64 64" preserveAspectRatio="xMinYMin m ...

Getting the chosen option from a dropdown menu with react.js

Having some trouble fetching the value of the selected dropdown option. The code snippet below is causing an error message to pop up: Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUp ...

Tips for aligning the timing of two CSS animations

I'm struggling to achieve a synchronized CSS animation where a progress bar fills up and a background changes simultaneously. For example, I want the progress bar to fill in 5000ms, with the background image changing every 5000ms as well. Despite se ...

What is the best way to ensure that a <label> remains vertically aligned with its <form>?

I'm struggling to incorporate their suggestions into my design. How can I align my label to the left of my input field on the same line? Also, I'm a beginner in coding so please excuse any mistakes in my code: body { background-color: #f5f ...

The `DataProvider` component received an invalid `data` prop of type `number` instead of the expected `array`. This issue is occurring within the context of using React-bootstrap

Lately, I've been working on fetching data from Firebase Realtime Database and then displaying it using react-bootstrap-table2. However, I've encountered a snag when attempting to actually render the data. Upon running my code, an error message p ...