• Stars
    star
    1,127
  • Rank 41,294 (Top 0.9 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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 [email protected]: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

More Repositories

1

react-copy-to-clipboard

Copy-to-clipboard React component
JavaScript
2,335
star
2

react-debounce-input

React component that renders Input with debounced onChange
JavaScript
451
star
3

react-height

Component-wrapper to determine and report children elements height
JavaScript
180
star
4

component-router

Redux-based component routing solution
JavaScript
93
star
5

react-component-template

Base for React Components
JavaScript
56
star
6

esnext-quickstart

Bring compilation and code validation to your front-end development process
JavaScript
55
star
7

react-works

🍇 Monorepo for React components
JavaScript
47
star
8

react-page-click

🏄🏻 **MOVED** React component-wrapper to detect page clicks (outside of wrapped element).
JavaScript
45
star
9

react-interval

🏄🏻 **MOVED** Safe React wrapper for setInterval
37
star
10

ng-modular

Truly modular Angular app, built with Webpack. Slides
JavaScript
36
star
11

react-motion-loop

Looping animation for react-motion Spring
JavaScript
28
star
12

react-text-filter

🏄🏻 **MOVED** React component that renders filtering Input
18
star
13

react-swap

🏄🏻 **MOVED** React component-wrapper to swap one element with another and back
18
star
14

nightwatch-autorun

Zero-configuration runner to automatically install and run End-to-End tests with Nightwatch and Selenium
JavaScript
14
star
15

react-normalized-select

🏄🏻 **MOVED** Normalized Select wrapper, returns array of values in multiple mode
14
star
16

react-element-resize

🏄🏻 **MOVED** Element resize sensor with optional debounce
10
star
17

vagrant-node

Bootstrap for Node development.
Scheme
8
star
18

css-modules-component-template

Styled UI component template with CSS-Modules
JavaScript
5
star
19

minicat

Windows compatible `cat` shell command polyfill
JavaScript
5
star
20

build

Automatic building with Grunt
JavaScript
3
star
21

geovis

GeoVis
JavaScript
3
star
22

node-girls

🎤 Slides for NodeGirls Sydney @ 1.0.0
JavaScript
2
star
23

un-responsive-demo

Demo app for Un.Responsive talk
JavaScript
2
star
24

gleam

Reusable models for the Node server and browsers
JavaScript
2
star
25

itunes-scrobbler

Scrobble retrospectively plays and loved tracks to Last.FM from iTunes database.
JavaScript
2
star
26

wtf-tf

Terraform for beginners, demystifying CI/CD for developers
HCL
2
star
27

cf-react-component-template

🚫 **DEPRECATED** React component template scaffold
JavaScript
2
star
28

flux-common-store

Common Flux store
JavaScript
2
star
29

react-component-router

Official ComponentRouter bindings for React
JavaScript
2
star
30

gleam-demo

Simple chat application to demo Gleam library.
CSS
2
star
31

react-bulkhead

🏄🏻 **MOVED** React component to allow 3rd party components to operate over DOM-tree (d3, three.js)
2
star
32

assemyskak.com

HTML
2
star
33

ui

Monorepo for UI components, React hooks, elements, no build, only sources
JavaScript
2
star
34

sydjs2

SydJS talk: Modular, please
1
star
35

oss

OpenSource Talk
JavaScript
1
star
36

scrobbler

Manual bulk scrobbler from text or json file to LastFM
JavaScript
1
star
37

opera-github-sidebar

Opera sidebar plugin for Github
JavaScript
1
star
38

haskell-book

HaskellBook exercises
Haskell
1
star
39

v7tabs

Restyled V7 Tabs Opera extension
JavaScript
1
star
40

sublime2-todo

TODO language and syntax highlight for Sublime Text 2
1
star
41

react-jasmine-matchers

🚫 **DEPRECATED** Custom matchers for ReactTestUtils
JavaScript
1
star
42

puma

Fast and simple framework for modular application
JavaScript
1
star
43

nnj

Node Ninjas talk
JavaScript
1
star
44

un-responsive

Un.Responsive talk for ReactSydney
JavaScript
1
star
45

cli-tester

Lean promisified wrapper to test NodeJS CLI scripts
JavaScript
1
star
46

geovis-standalone

GeoVis Standalone
JavaScript
1
star
47

event-done

Extension of EventEmitter which allows to pass callback that will be invoked when all listeners completed
JavaScript
1
star
48

wscli

WebSocket CLI util
JavaScript
1
star
49

css-modules-component-template-test

Example consumer app for css-modules-component-template
1
star