Convert Figma logo to code with AI

nkbt logoreact-collapse

Component-wrapper for collapse animation with react-motion for elements with variable (and dynamic) height

1,120
113
1,120
10

Top Related Projects

An easy way to perform animations when a React component enters or leaves the DOM

23,338

Open source, production-ready animation and gesture library for React

✌️ A spring physics based React animation library

Effortless animation between DOM changes (eg. list reordering) using the FLIP technique.

React components for Chart.js, the most popular charting library

Quick Overview

React-collapse is a lightweight and flexible React component for creating collapsible content with smooth animations. It allows developers to easily implement expandable/collapsible sections in their React applications, providing a clean and customizable solution for managing content visibility.

Pros

  • Simple API and easy integration with existing React projects
  • Smooth animations for expanding and collapsing content
  • Highly customizable with support for custom styles and animations
  • Small bundle size, minimizing impact on application performance

Cons

  • Limited built-in styling options, requiring additional CSS for more complex designs
  • Lack of advanced features like accordion-style behavior out of the box
  • Documentation could be more comprehensive, especially for advanced use cases
  • Relatively small community compared to some other React UI libraries

Code Examples

  1. Basic usage:
import { Collapse } from 'react-collapse';

function App() {
  const [isOpened, setIsOpened] = useState(false);

  return (
    <div>
      <button onClick={() => setIsOpened(!isOpened)}>Toggle</button>
      <Collapse isOpened={isOpened}>
        <div>Collapsible content here</div>
      </Collapse>
    </div>
  );
}
  1. Using custom styles:
import { Collapse } from 'react-collapse';

function App() {
  return (
    <Collapse
      isOpened={true}
      theme={{
        collapse: 'custom-collapse-class',
        content: 'custom-content-class'
      }}
    >
      <div>Styled collapsible content</div>
    </Collapse>
  );
}
  1. Nested collapses:
import { Collapse } from 'react-collapse';

function NestedCollapses() {
  return (
    <Collapse isOpened={true}>
      <div>Outer content</div>
      <Collapse isOpened={true}>
        <div>Inner content</div>
      </Collapse>
    </Collapse>
  );
}

Getting Started

  1. Install the package:
npm install react-collapse
  1. Import and use the Collapse component in your React application:
import React, { useState } from 'react';
import { Collapse } from 'react-collapse';

function MyComponent() {
  const [isOpened, setIsOpened] = useState(false);

  return (
    <div>
      <button onClick={() => setIsOpened(!isOpened)}>Toggle</button>
      <Collapse isOpened={isOpened}>
        <p>This content can be collapsed and expanded.</p>
      </Collapse>
    </div>
  );
}

export default MyComponent;

Competitor Comparisons

An easy way to perform animations when a React component enters or leaves the DOM

Pros of react-transition-group

  • More comprehensive animation capabilities, supporting enter, exit, and appear transitions
  • Official React library, ensuring better long-term support and compatibility
  • Flexible API that can be used for various transition scenarios beyond just collapsing elements

Cons of react-transition-group

  • Steeper learning curve due to its more complex API
  • Requires more setup and configuration for simple collapse animations
  • May introduce unnecessary overhead for projects that only need basic collapse functionality

Code Comparison

react-collapse:

<Collapse isOpened={isOpened}>
  <div>Collapsible content</div>
</Collapse>

react-transition-group:

<CSSTransition in={isOpened} timeout={300} classNames="collapse">
  <div>Collapsible content</div>
</CSSTransition>

Summary

react-collapse is more focused and easier to use for simple collapse animations, while react-transition-group offers greater flexibility and animation capabilities at the cost of increased complexity. The choice between the two depends on the specific project requirements and the desired level of animation control.

23,338

Open source, production-ready animation and gesture library for React

Pros of motion

  • More comprehensive animation library with a wider range of features
  • Better performance due to GPU acceleration and optimized rendering
  • Larger community and more frequent updates

Cons of motion

  • Steeper learning curve due to more complex API
  • Larger bundle size, which may impact initial load times
  • Potentially overkill for simple animations or transitions

Code Comparison

react-collapse:

<Collapse isOpened={isOpen}>
  <div>Content to be collapsed</div>
</Collapse>

motion:

<motion.div
  initial={{ height: 0 }}
  animate={{ height: isOpen ? "auto" : 0 }}
  transition={{ duration: 0.3 }}
>
  <div>Content to be collapsed</div>
</motion.div>

Summary

motion offers a more powerful and versatile animation solution, while react-collapse provides a simpler, more focused approach to collapsible components. motion is better suited for projects requiring complex animations across various elements, while react-collapse is ideal for straightforward collapse/expand functionality with minimal setup. The choice between the two depends on the specific needs of your project, considering factors such as animation complexity, performance requirements, and development time constraints.

✌️ A spring physics based React animation library

Pros of react-spring

  • More versatile animation library, offering a wide range of animation types beyond just collapsing
  • Physics-based animations for more natural and fluid motion
  • Larger community and more frequent updates

Cons of react-spring

  • Steeper learning curve due to its more comprehensive API
  • Potentially overkill for simple collapse animations
  • Larger bundle size, which may impact performance in smaller projects

Code Comparison

react-collapse:

<Collapse isOpened={isOpen}>
  <div>Content to be collapsed</div>
</Collapse>

react-spring:

import { useSpring, animated } from 'react-spring'

const props = useSpring({
  height: isOpen ? 'auto' : 0,
  opacity: isOpen ? 1 : 0,
})

<animated.div style={props}>
  <div>Content to be collapsed</div>
</animated.div>

react-collapse is more straightforward for simple collapse animations, while react-spring offers more control and flexibility but requires more setup. react-spring's approach allows for smoother, physics-based animations and can be easily extended to other animation types, making it a more powerful tool for complex animation needs. However, for projects that only require basic collapse functionality, react-collapse may be the simpler and more lightweight option.

Effortless animation between DOM changes (eg. list reordering) using the FLIP technique.

Pros of react-flip-move

  • More versatile, supporting various animation types beyond just collapsing
  • Smoother animations with FLIP technique for better performance
  • Extensive documentation and examples

Cons of react-flip-move

  • Slightly more complex setup and configuration
  • May be overkill for simple collapse/expand animations
  • Larger bundle size due to additional features

Code Comparison

react-collapse:

<Collapse isOpened={isOpen}>
  <div>Content to collapse</div>
</Collapse>

react-flip-move:

<FlipMove enterAnimation="fade" leaveAnimation="fade">
  {items.map(item => (
    <div key={item.id}>{item.content}</div>
  ))}
</FlipMove>

Summary

react-collapse is simpler and more focused on collapse/expand animations, while react-flip-move offers a broader range of animation possibilities. react-flip-move provides smoother animations and better performance for complex list transitions, but it may be unnecessary for basic collapsing needs. react-collapse is easier to set up and has a smaller footprint, making it ideal for simpler use cases. Choose react-flip-move for more advanced animations and react-collapse for straightforward expand/collapse functionality.

React components for Chart.js, the most popular charting library

Pros of react-chartjs-2

  • Provides a wide range of chart types and customization options
  • Integrates seamlessly with Chart.js, a popular charting library
  • Offers responsive and interactive charts out of the box

Cons of react-chartjs-2

  • Larger bundle size due to the inclusion of Chart.js
  • Steeper learning curve for complex chart configurations
  • May require additional setup for advanced features

Code Comparison

react-chartjs-2:

import { Line } from 'react-chartjs-2';

const data = {
  labels: ['January', 'February', 'March'],
  datasets: [{ data: [65, 59, 80], label: 'Sales' }]
};

<Line data={data} />

react-collapse:

import { Collapse } from 'react-collapse';

<Collapse isOpened={isOpened}>
  <p>Collapsible content</p>
</Collapse>

Summary

react-chartjs-2 is a powerful charting library for React applications, offering a wide range of chart types and customization options. It integrates well with Chart.js and provides responsive, interactive charts. However, it comes with a larger bundle size and may require more setup for advanced features.

react-collapse, on the other hand, is a simpler component focused on creating collapsible elements. It has a smaller footprint and is easier to implement for basic collapse functionality. However, it lacks the extensive visualization capabilities of react-chartjs-2.

Choose react-chartjs-2 for complex data visualization needs, and react-collapse for simple collapsible UI elements.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-collapse npm

Gitter

CircleCI Dependencies Dev Dependencies

Component-wrapper for collapse animation for elements with variable (and dynamic) height

React Collapse

Demo

http://nkbt.github.io/react-collapse

Codepen demo

http://codepen.io/nkbt/pen/MarzEg

Installation

NPM

npm install --save react-collapse

yarn

yarn add react-collapse

1998 Script Tag:

<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-collapse/build/react-collapse.min.js"></script>
(Module exposed as `ReactCollapse`)

Usage

1. Add a CSS transition

.ReactCollapse--collapse {
  transition: height 500ms;
}

IMPORTANT: Without adding a CSS transition there will be no animation and component will open/close instantly.

2. Content is always mounted (default)

import {Collapse} from 'react-collapse';

// ...
<Collapse isOpened={true || false}>
  <div>Random content</div>
</Collapse>

3. Content unmounts when collapsed

Use Unmount component provided as:

import {UnmountClosed} from 'react-collapse';

// ...
<UnmountClosed isOpened={true || false}>
  <div>Random content</div>
</UnmountClosed>

Example example/App/AutoUnmount.js


4. Controlled and accessible

If you want a controlled and accessible implementation, check out this example

Options

isOpened: PropTypes.boolean.isRequired

Expands or collapses content.

children: PropTypes.node.isRequired

One or multiple children with static, variable or dynamic height.

<Collapse isOpened={true}>
  <p>Paragraph of text</p>
  <p>Another paragraph is also OK</p>
  <p>Images and any other content are ok too</p>
  <img src="nyancat.gif" />
</Collapse>

theme: PropTypes.objectOf(PropTypes.string)

It is possible to set className for extra div elements that ReactCollapse creates.

Example:

<Collapse theme={{collapse: 'foo', content: 'bar'}}>
  <div>Customly animated container</div>
</Collapse>

Default values:

const theme = {
  collapse: 'ReactCollapse--collapse',
  content: 'ReactCollapse--content'
}

Which ends up in the following markup:

<div class="ReactCollapse--collapse">
  <div class="ReactCollapse--content">
    {children}
  </div>
</div>

IMPORTANT: these are not style objects, but class names!

onRest, onWork: PropTypes.func

Callback functions, triggered when animation has completed (onRest) or has just started (onWork)

Both functions are called with argument:

const arg = {
  isFullyOpened: true || false, // `true` only when Collapse reached final height
  isFullyClosed: true || false, // `true` only when Collapse is fully closed and height is zero
  isOpened: true || false, // `true` if Collapse has any non-zero height
  containerHeight: 123, // current pixel height of Collapse container (changes until reaches `contentHeight`)
  contentHeight: 123 // determined height of supplied Content
}
<Collapse onRest={console.log} onWork={console.log}>
  <div>Container text</div>
</Collapse>

Example example/App/Hooks.js

initialStyle: PropTypes.shape

initialStyle: PropTypes.shape({
  height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  overflow: PropTypes.string
})

You may control initial element style, for example to force initial animation from 0 to height by using initialStyle={{height: '0px', overflow: 'hidden'}}

IMPORTANT Any updates to this prop will be ignored after first render. Default value is determined based on initial isOpened value:

  initialStyle = props.isOpened
    ? {height: 'auto', overflow: 'initial'}
    : {height: '0px', overflow: 'hidden'};

Example: example/App/ForceInitialAnimation.js

checkTimeout: PropTypes.number

Number in ms.

Collapse will check height after thins timeout to determine if animation is completed, the shorter the number - the faster onRest will be triggered and the quicker height: auto will be applied. The downside - more calculations. Default value is: 50.

Pass-through props

IMPORTANT Collapse does not support any pass-through props, so any non-supported props will be ignored

Because we need to have control over when Collapse component is updated and it is not possible or very hard to achieve when any random props can be passed to the component.

Behaviour notes

  • initially opened Collapse elements will be statically rendered with no animation. You can override this behaviour by using initialStyle prop

  • due to the complexity of margins and their potentially collapsible nature, ReactCollapse does not support (vertical) margins on their children. It might lead to the animation "jumping" to its correct height at the end of expanding. To avoid this, use padding instead of margin. See #101 for more details

Migrating from v4 to v5

v5 was another complete rewrite that happened quite a while ago, it was published as @nkbt/react-collapse and tested in real projects for a long time and now fully ready to be used.

In the most common scenario upgrade is trivial (add CSS transition to collapse element), but if you were using a few deprecated props - there might be some extra work required.

Luckily almost every deprecated callback or prop has fully working analogue in v5. Unfortunately not all of them could maintain full backward compatibility, so please check this migration guide below.

1. Change in behaviour

New Collapse does not implement animations anymore, it only determines Content height and updates Collapse wrapper height to match it. Only after Collapse height reaches Content height (animation finished), Collapse's style is updated to have height: auto; overflow: initial.

The implications is that you will need to update your CSS with transition:

.ReactCollapse--collapse {
  transition: height 500ms;
}

IMPORTANT: Without adding a CSS transition there will be no animation and component will open/close instantly.

2. New props or updated props

  • onRest/onWork callbacks (see above for full description). Though onRest did exist previously, now it is called with arguments containing few operational params and flags.

  • initialStyle you may control initial element style, for example to force initial animation from 0 to height by using initialStyle={{height: '0px', overflow: 'hidden'}} IMPORTANT Any updates to this prop will be ignored after first render. Default value is:

      initialStyle = props.isOpened
        ? {height: 'auto', overflow: 'initial'}
        : {height: '0px', overflow: 'hidden'};
    
  • checkTimeout number in ms. Collapse will check height after thins timeout to determine if animation is completed, the shorter the number - the faster onRest will be triggered and the quicker height: auto will be applied. The downside - more calculations. Default value is: 50.

3. Deprecated props (not available in v5)

  • Pass-through props - any unknown props passed to Collapse component will be ignored

  • hasNestedCollapse - no longer necessary, as v5 does not care if there are nested Collapse elements, see example/App/Nested.js

  • fixedHeight - no longer necessary, just set whatever height you need for content element and Collapse will work as expected, see example/App/VariableHeight.js

  • springConfig - as new Collapse relies on simple CSS transitions (or your own implementation of animation) and does not use react-collapse, springConfig is no longer necessary. You can control control animation with css like

    .ReactCollapse--collapse {
      transition: height 500ms;
    }
    
  • forceInitialAnimation - you can use new prop initialStyle={{height: '0px', overflow: 'hidden'}} instead, so when new height will be set after component is rendered - it should naturally animate.

  • onMeasure - please use onRest and onWork instead and pick contentHeight from argument

    <Collapse
      onRest={({contentHeight}) => console.log(contentHeight)}
      onWork={({contentHeight}) => console.log(contentHeight)}>
      <div>content</div>
    </Collapse>
    
  • onRender - since animations are fully controlled by external app (e.g. with CSS) we no draw each frame and do not actually re-render component anymore, so it is impossible to have onRender callback

Development and testing

Currently is being developed and tested with the latest stable Node on OSX.

To run example covering all ReactCollapse features, use yarn start, which will compile example/Example.js

git clone git@github.com:nkbt/react-collapse.git
cd react-collapse
yarn install
yarn start

# then
open http://localhost:8080

Tests

# to run ESLint check
yarn lint

# to run tests
yarn test

License

MIT

NPM DownloadsLast 30 Days