GithubHelp home page GithubHelp logo

kunukn / react-collapse Goto Github PK

View Code? Open in Web Editor NEW
162.0 4.0 18.0 3.21 MB

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

License: MIT License

JavaScript 16.49% CSS 2.30% HTML 9.57% TypeScript 62.59% SCSS 9.04%
accordion collapsible css-transition react codesandbox codepen

react-collapse's Introduction

react-collapse

Collapse component with CSS transition for elements with variable and dynamic height.

npm version npm downloads gzip license

react-collapse

logo

Demo

CSS required

⚠️ ️You need to add style (transition) in your own stylesheet to add animation. Here is an example.

<style>
  .collapse-css-transition {
    transition: height 280ms cubic-bezier(0.4, 0, 0.2, 1);
  }
</style>

Alternatively, you can add it using the transition prop.

Installation for React 16.8+

  • UMD minified ~2.3 kb, gzipped ~1.1 kb
  • Module minified ~2.9 kb, gzipped ~1.1 kb
  • CJS minified ~2.0 kb, gzipped ~1.0 kb
npm i -D @kunukn/react-collapse
# or
# yarn add -D @kunukn/react-collapse

Installation for React 16.3+

Avoid it if possible. This is no longer maintained.

  • UMD minified ~5.8 kb, gzipped ~2.1 kb
npm i -D @kunukn/react-collapse@^1
# or
# yarn add -D @kunukn/react-collapse@^1

Minimal toggle content component example.

// Notice how you import it, changed since ver 3.
import { Collapse } from '@kunukn/react-collapse'
import React from 'react'

export default function MyComponent() {
  const [isOpen, setIsOpen] = React.useState(false)
  const onToggle = () => setIsOpen((s) => !s)

  return (
    <div className="my-component">
      <button onClick={onToggle}> Toggle </button>
      <Collapse
        isOpen={isOpen}
        transition="height 300ms cubic-bezier(0.4, 0, 0.2, 1)"
      >
        <p> Hello world </p>
      </Collapse>
    </div>
  )
}
// The possible imports

import { Collapse } from '@kunukn/react-collapse' // UMD
import '@kunukn/react-collapse/dist/react-collapse.css' // CSS
import type { CollapseProps } from '@kunukn/react-collapse/dist/react-collapse.d.ts' // TS
const { Collapse } = require('@kunukn/react-collapse/dist/react-collapse.cjs') // CommonJS

Properties

Prop Type Default
isOpen boolean false
children node | function
render function
className string collapse-css-transition
transition string
elementType string div
collapseHeight string 0px
onChange function
onInit function
addState boolean false
noAnim boolean false
overflowOnExpanded boolean false

isOpen : boolean

Expands or collapses content.

children : node | function

Render the children.

const MyComponent = ({ isOpen }) => (
  <Collapse isOpen={isOpen}>
    <p>Paragraph of text.</p>
    <p>Another paragraph is also OK.</p>
    <p>Images and any other content are ok too.</p>
    <img src="cutecat.gif" />
  </Collapse>
)

Render content using the render-props pattern.

const MyComponent = ({ isOpen }) => (
  <Collapse isOpen={isOpen}>
    {(state) => (
      <div className={`using-collapse-state-to-add-css-class ${state}`}>
        <p>I know the collapse state: {state}</p>
      </div>
    )}
  </Collapse>
)

render : function

Render content using the render-props pattern.

const MyComponent = ({ isOpen }) => {
  const render = (state) => (
    <div className={`using-collapse-state-to-add-css-class ${state}`}>
      <p>I know the collapse state: {state}</p>
    </div>
  )
  return <Collapse isOpen={isOpen} render={render} />
}

There are four possible collapse states: collapsed, collapsing, expanded, expanding.

className : string

You can specify a custom className. The default value is collapse-css-transition. Remember to add CSS transition if a className is provided.

transition : string

You can also specify a CSS transition inline by using the transition prop.

const MyComponent = ({ isOpen, duration = '290ms' }) => (
  <Collapse
    transition={`height ${duration} cubic-bezier(.4, 0, .2, 1)`}
    isOpen={isOpen}
  >
    <p>Paragraph of text</p>
  </Collapse>
)

elementType : string

You can specify the HTML element type for the collapse component. By default, the element type is a div element.

const MyComponent = ({ isOpen }) => (
  <Collapse elementType="article" isOpen={isOpen}>
    <p>Paragraph of text inside an article element</p>
  </Collapse>
)

collapseHeight : string

You can specify the collapse height in CSS unit to partially show some content.

const MyComponent = ({ isOpen }) => (
  <Collapse collapseHeight="40px" isOpen={isOpen}>
    <p>A long paragraph of text inside an article element</p>
  </Collapse>
)

onChange : function

Callback function for when the transition changes.

const MyComponent = ({ isOpen }) => {
  const onChange = ({ state, style }) => {
    /*
    state: string = the state of the collapse component.
    style: object = styles that are applied to the component.
  */
  }

  return (
    <Collapse onChange={onChange} isOpen={isOpen}>
      <p>A long paragraph of text inside an article element</p>
    </Collapse>
  )
}

onInit : function

Similar to onChange but only invoked on DOM mounted.
This is an example that starts collapsed and expands on mount.

const MyComponent = () => {
  const [isOpen, setIsOpen] = React.useState(false)

  const onInit = ({ state, style, node }) => {
    /*
       node: HTMLElement = the DOM node of the component.
    */

    setIsOpen(true)
  }

  return (
    <div>
      <button onClick={() => setIsOpen((state) => !state)}> Toggle </button>
      <Collapse onInit={onInit} isOpen={isOpen}>
        <p>A long paragraph of text inside an article element</p>
      </Collapse>
    </div>
  )
}

addState : boolean

If added, then one of the class names will be appended to the component depending on the state.

--c-collapsed
--c-collapsing
--c-expanded
--c-expanding

noAnim : boolean

If added, then there will be no collapse animation. State changes between collapsed and expanded.

overflowOnExpanded : boolean

If added, then overflow: hidden style will not be added when the state is expanded.

Custom props

Collapse applies custom props such as aria- and data- attributes to the component's rendered DOM element. For example, this can be used to set the aria-hidden attribute:

const MyComponent = ({ isOpen }) => (
  <Collapse aria-hidden={isOpen ? 'false' : 'true'} isOpen={isOpen}>
    <p>Paragraph of text</p>
  </Collapse>
)

Or you could specify a specific transitionDuration.

const collapseStyles = { transitionDuration: '270ms' }

const MyComponent = ({ isOpen }) => (
  <Collapse style={collapseStyles} isOpen={isOpen}>
    <p>Paragraph of text</p>
  </Collapse>
)

Development

To run development

npm start

git clone [repo]
cd [repo]
npm i
npm start
  • To develop and play around: npm start
  • To build the bundle: npm run build

CDN

https://unpkg.com/@kunukn/react-collapse/

<link
  rel="stylesheet"
  href="https://unpkg.com/@kunukn/react-collapse/dist/react-collapse.css"
/>
<!-- UMD -->
<script src="https://unpkg.com/@kunukn/react-collapse"></script>

NPM

https://www.npmjs.com/package/@kunukn/react-collapse

Supported browsers

Modern browsers (Edge, Firefox, Chrome, Safari, etc).

Supported React versions

  • React version 16.3+ : use Collapse version 1
  • React version 16.8+ : use Collapse version 2+

Used React 16.3 life-cycles

  • render (uses the style states to invoke CSS transition)
  • componentDidMount (initial expanded or collapsed state)
  • getDerivedStateFromProps (detect if isOpen props have changed and apply a new collapse state)
  • componentDidUpdate (update style states from the four possible collapse states)

Used React 16.8+ hooks

  • useState
  • useEffect
  • useRef
  • useCallback
  • useReducer

Design goals

  • let the browser handle the animation using CSS height transition
  • minimal in file size
  • minimalistic API - only have a Collapse component which updates on isOpen props
  • flexible - provide your own markup, styling and easing
  • interruptible - can be reversed during movement
  • inert - when collapsed you should tab over the collapsed component
  • availability - from cdn or npm install
  • collapsible on height only

This was created with heavy inspiration from

https://github.com/SparebankenVest/react-css-collapse 🎆

A version also exists for Vue

https://github.com/kunukn/vue-height-collapsible

react-collapse's People

Contributors

dependabot[bot] avatar kunukn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-collapse's Issues

Getting lot of errors when I run **npm install**

Hi all, I downloaded the package and ran npm install. I got so many errors, what could be the reason.

npm ERR! code 1
npm ERR! path C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\node-sass
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node scripts/build.js
npm ERR! Building: C:\Program Files\nodejs\node.exe C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp verb cli [
npm ERR! gyp verb cli   'C:\\Program Files\\nodejs\\node.exe',
npm ERR! gyp verb cli   'C:\\Users\\kashok\\Downloads\\react-collapse-master\\node_modules\\rollup-plugin-scss\\node_modules\\node-gyp\\bin\\node-gyp.js',
npm ERR! gyp verb cli   'rebuild',
npm ERR! gyp verb cli   '--verbose',
npm ERR! gyp verb cli   '--libsass_ext=',
npm ERR! gyp verb cli   '--libsass_cflags=',
npm ERR! gyp verb cli   '--libsass_ldflags=',
npm ERR! gyp verb cli   '--libsass_library='
npm ERR! gyp verb cli ]
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | win32 | x64
npm ERR! gyp verb command rebuild []
npm ERR! gyp verb command clean []
npm ERR! gyp verb clean removing "build" directory
npm ERR! gyp verb command configure []
npm ERR! gyp verb check python checking for Python executable "python2" in the PATH
npm ERR! gyp verb `which` failed Error: not found: python2
npm ERR! gyp verb `which` failed     at getNotFoundError (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:13:12)
npm ERR! gyp verb `which` failed     at F (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:68:19)
npm ERR! gyp verb `which` failed     at E (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:80:29)
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:89:16
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\isexe\index.js:42:5
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\isexe\windows.js:36:5
npm ERR! gyp verb `which` failed     at FSReqCallback.oncomplete (node:fs:198:21)
npm ERR! gyp verb `which` failed  python2 Error: not found: python2
npm ERR! gyp verb `which` failed     at getNotFoundError (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:13:12)
npm ERR! gyp verb `which` failed     at F (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:68:19)
npm ERR! gyp verb `which` failed     at E (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:80:29)
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:89:16
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\isexe\index.js:42:5
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\isexe\windows.js:36:5
npm ERR! gyp verb `which` failed     at FSReqCallback.oncomplete (node:fs:198:21) {
npm ERR! gyp verb `which` failed   code: 'ENOENT'
npm ERR! gyp verb `which` failed }
npm ERR! gyp verb check python checking for Python executable "python" in the PATH
npm ERR! gyp verb `which` failed Error: not found: python
npm ERR! gyp verb `which` failed     at getNotFoundError (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:13:12)
npm ERR! gyp verb `which` failed     at F (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:68:19)
npm ERR! gyp verb `which` failed     at E (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:80:29)
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:89:16
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\isexe\index.js:42:5
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\isexe\windows.js:36:5
npm ERR! gyp verb `which` failed     at FSReqCallback.oncomplete (node:fs:198:21)
npm ERR! gyp verb `which` failed  python Error: not found: python
npm ERR! gyp verb `which` failed     at getNotFoundError (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:13:12)
npm ERR! gyp verb `which` failed     at F (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:68:19)
npm ERR! gyp verb `which` failed     at E (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:80:29)
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\which\which.js:89:16
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\isexe\index.js:42:5
npm ERR! gyp verb `which` failed     at C:\Users\kashok\Downloads\react-collapse-master\node_modules\isexe\windows.js:36:5
npm ERR! gyp verb `which` failed     at FSReqCallback.oncomplete (node:fs:198:21) {
npm ERR! gyp verb `which` failed   code: 'ENOENT'
npm ERR! gyp verb `which` failed }
npm ERR! gyp verb could not find "python". checking python launcher
npm ERR! gyp verb could not find "python". guessing location
npm ERR! gyp verb ensuring that file exists: C:\Python27\python.exe
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
npm ERR! gyp ERR! stack     at PythonFinder.failNoPython (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\node-gyp\lib\configure.js:484:19)
npm ERR! gyp ERR! stack     at PythonFinder.<anonymous> (C:\Users\kashok\Downloads\react-collapse-master\node_modules\rollup-plugin-scss\node_modules\node-gyp\lib\configure.js:509:16)
npm ERR! gyp ERR! stack     at FSReqCallback.oncomplete (node:fs:198:21)
npm ERR! gyp ERR! System Windows_NT 10.0.19042
npm ERR! gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\kashok\\Downloads\\react-collapse-master\\node_modules\\rollup-plugin-scss\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
npm ERR! gyp ERR! node -v v16.13.1
npm ERR! gyp ERR! not ok
npm ERR! Build failed with error code: 1

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\kashok\AppData\Local\npm-cache\_logs\2022-02-02T16_03_53_452Z-debug.log
PS C:\Users\kashok\Downloads\react-collapse-master> npm uninstall
npm ERR! Must provide a package name to remove

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\kashok\AppData\Local\npm-cache\_logs\2022-02-02T16_06_12_283Z-debug.log

Thank you.

Media query / breakpoint support

Scenario:

  • For small screen/browser widths (using media query), use Collapse's logic
  • For large screen/browser widths, always show (do not show toggle button)

Problem:

  • If you start with isOpen false, then on small screen the menu will work as expected, however on a large screen it will be hidden.
  • If you start with isOpen true, the menu will appear on a large screen, but on the small screen it will be expanded by default.

Feature request:

Allow wrapping of the style that Collapse produces into a media query, making Collapse's effect applicable only on some screen widths.

Missing files in package

I have noticed that the following fields in package.json point to files that are not being published in the package.

 "module": "dist/Collapse.es.js",
  "cjs": "dist/Collapse.cjs.js",
  "iife": "dist/Collapse.iife.js",

Ran into an issue using babel-eslint and eslint-plugin-import

first accordion open by default

Hello, can anyone provide me example how i can implement situation when first accordion is open by default? Much appreciate.

The library code structure should be updated

When I started, I wanted to learn by manually configuring everything myself.
Years has passed and a lot of package versions is given headache when trying to update the versions.
And manually updating the obsolete API usage is too time-consuming and pain-full.

For future version something like this should be used instead.
https://github.com/jaredpalmer/tsdx

And scrap all the manual configuration and long npm scripts.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.