Techscrypt

ReactJS collapsible component with dynamic height

reactjsjavascript

Introduction

In order to create a collapsible component which may have dynamic
height, let us first look at a simple example of creating a collapsible
component with fixed height

This is simple since we know the height of the content, and we can set
it to 180px, when toggled.

Now if the content was dynamically loaded (say from an API call), it is
not possible to hard code the height of the content component. And css
transition does not work with height: auto

Solution

There are 2 ways to solve this

  1. Add a max-height with css transition — since that transition is
    supported. However it requires estimating max height that the content
    can take. Also, the animation would not be smooth if the value of
    max-height is too large compared to the content. (ref:link)

  2. Calculate height of the content and set the wrapper to that height.
    Since approach 1 has issues with the animation and doesn’t work well if
    there is large variation in the content height, approach 2 is better.

Implementation

Here is how that implementation looks in react:

Here, we use react ref to get the content element’s height. (react documentation reference) This can be set when the component is opened, and transition works.