Giter VIP home page Giter VIP logo

collapse's Introduction

rc-collapse

rc-collapse ui component for react

NPM version build status Test coverage npm download

Live Demo

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

Install

rc-collapse

Usage

var Collapse = require('rc-collapse');
var Panel = Collapse.Panel;
var React = require('react');
var ReactDOM = require('react-dom');
require('rc-collapse/assets/index.css');

var App = (
  <Collapse accordion={true}>
    <Panel header="hello" headerClass="my-header-class">
      this is panel content
    </Panel>
    <Panel header="title2">this is panel content2 or other</Panel>
  </Collapse>
);
ReactDOM.render(App, container);

Features

  • support ie8,ie8+,chrome,firefox,safari

API

Collapse props

name type default description
activeKey String|Array The first panel key current active Panel key
className String or object custom className to apply
defaultActiveKey String|Array null default active key
destroyInactivePanel Boolean false If destroy the panel which not active, default false.
accordion Boolean false accordion mode, default is null, is collapse mode
onChange Function(key) noop called when collapse Panel is changed
expandIcon (props: PanelProps) => ReactNode specific the custom expand icon.
collapsible 'header' | 'icon' | 'disabled' - specify whether the panel of children is collapsible or the area of collapsible.
items interface.ts#ItemType - collapse items content

If accordion is null or false, every panel can open. Opening another panel will not close any of the other panels. activeKey should be an string, if passing an array (the first item in the array will be used).

If accordion is true, only one panel can be open. Opening another panel will cause the previously opened panel to close. activeKey should be an string, if passing an array (the first item in the array will be used).

Collapse.Panel props

deprecated use items instead, will be removed in v4.0.0

name type default description
header String or node header content of Panel
headerClass String ' ' custom className to apply to header
showArrow boolean true show arrow beside header
className String or object custom className to apply
style object custom style
openMotion object set the animation of open behavior, [more](https://github.com/react-component/motion). Different with v2, closed pane use a `rc-collapse-content-hidden` class to set `display: none` for hidden.
forceRender boolean false forced render of content in panel, not lazy render after clicking on header
extra String | ReactNode Content to render in the right of the panel header
collapsible 'header' | 'icon' | 'disabled' - specify whether the panel be collapsible or the area of collapsible.

disabled is removed since 3.0.0, please use collapsible=disabled replace it.

key

If key is not provided, the panel's index will be used instead.

KeyBoard Event

By default, Collapse will listen onKeyDown(<3.7.0 onKeyPress) event with enter key to toggle panel's active state when collapsible is not disabled. If you want to disable this behavior, you can prevent the event from bubbling like this:

const App = () => {
  const items: CollapseProps['items'] = [
    {
      label: <input onKeyDown={(e) => e.stopPropagation()} />,
      children: 'content',
    },
    {
      label: (
        <div onKeyDown={(e) => e.stopPropagation()}>
          <CustomComponent />
        </div>
      ),
      children: 'content',
    },
    {
      label: 'title 2',
      children: 'content 2',
      collapsible: 'disabled',
    },
    {
      label: 'title 3',
      children: 'content 3',
      onItemClick: console.log,
    },
  ];

  return <Collapse items={items} />;
};

Development

npm install
npm start

Test Case

npm test

Coverage

npm test -- --coverage

License

rc-collapse is released under the MIT license.

collapse's People

Contributors

afc163 avatar benjycui avatar bertho-zero avatar dependabot-preview[bot] avatar dependabot-support avatar dependabot[bot] avatar dolov avatar gyh9457 avatar heskeybaozi avatar kerm1it avatar kiner-tang avatar kossel avatar lgtm-com[bot] avatar madccc avatar match-yichaozhu avatar sheepeer avatar shepherdwind avatar valerykrukovich avatar wxh16144 avatar xrkffgg avatar xyuanbuilds avatar y-yagi avatar y-young avatar yesmeck avatar yiminghe avatar yoyo837 avatar ystarlongzi avatar zombiej avatar ztplz avatar zwkang 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  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

collapse's Issues

Set Initial state for open panels

Hi.

I want to display a collapse with open panels. The user can close them later.

If I don't set activeKey, collapse will mount with closed panels. If I set activeKey with an array, panels will be open, but I can't close them later.

Maybe an initialActiveKey prop in the Collapse, or maybe a boolean prop for each panel?

EDIT: ok, I saw it now, it's the defaultActiveKey prop that does this.

How to render wrapped Panel under Collapse?

// MyPanel.jsx
return (
  <Collapse.Panel>
    ...
  </Collapse.Panel>
)

// List.jsx
return (
  <Collapse>
    {xs.map((x) => <MyPanel {...x} />)}
  </Collapse>
)

Since List.jsx and MyPanel.jsx contains complex business, spilt Collapse and Panel into two files.But it doesn't work.

So how to render wrapped Panel under Collapse?

React 0.14 Compatibility

This project is not technically React 0.14 compatible since one of its dependencies is not: rc-animate.

When using rc-collapse w/ React 0.14, you'll get the following warning/error in the console:

Warning: React.findDOMNode is deprecated. Please use ReactDOM.findDOMNode from require('react-dom') instead.

I have create this PR to update the dependencies:

rc-animate: react-component/animate#4

Animation lagging

After the 1.5.0 upgrade that includes the switch to using CSS animations, the open/close animation is very slow and lags in all browsers.

React PropTypes and React.createClass deprecation warnings

When including rc-collapse in a React 15.5.* project, two warnings always appear. When React 16 is released, this package will be broken.

  • Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.
  • Warning: AnimateChild: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.

The fix for the proptype warning is pretty simple, just adding a dependency to the replacement package prop-types and adding import PropTypes from 'prop-types'; to any source file with a PropType reference.

Programmatically setting the expand/collapse state

I am not able to programatically set the state of the Panel. I've tried setting <Panel isActive={true} /> but it doesn't seem to work. I've tried setting <Collapse activeKey='0'>.... and while this works, it only lets me specify one panel to be opened. The docs mention passing an array to activeKey, but I couldn't get it to work, and couldn't find any examples of it.

In my case, I need all the panels to be expanded at startup by default. Any idea how I can do this?

accordion={true} not working

If accordion is true, only one panel can be open. Opening another panel will cause the previously opened panel to close. activeKey should be an string, if passing an array (the first item in the array will be used).

Here's my snippet:


  render(){
    const stateStyle = this.state.active ? styles.active : styles.inactive;

    const Materias = this.props.items.map((item, key)=>(
        <Panel header={item.title} key={key}>
          <HeaderComponent title={item.title} id={item.id} subtitle={item.subtitle} category={item.categoria}/>
          <Content content={item.content[0]}/>
          <Footer />
        </Panel>
    )); 
    return (
      <div className={style.container}>
        <Collapse accordion={true}>
          {Materias}
        </Collapse>
      </div>
    );
  }

Actually im rendering 3 panels, and even with the accordion prop = true_ I can open the 3 at the same time.

Conditional <Panel /> makes rc-collapse crash on child.key

Hi,

I'm conditionally putting <Panel />s like this:

{ content.location &&
<Panel header="Location" key="4">
   <p>
       {content.location.value}
   </p>
</Panel>
}

However, when the evaluation of content.location returns false, and no <Panel /> is inserted, rc-collapse breaks because it expects a child with a .key property:

TypeError: null is not an object (evaluating 'child.key')

If rc-collapse would check if child exists before reading key, it would allow us to dynamically insert <Panel />s based on conditions, like in the example above.

I get a React Warning when rendering divs as children in Collapse component

My looks like this:

<Collapse
  accordion
  activeKey={this.state.activeKey}
  onChange={(activeKey) => this.setState({ activeKey })}>
  <Panel header='test'>
    ...
  </Panel>
  <div>
    Content that I don't want to be included in the accordion
  </div>
  <Panel header='also a test'>
    ...
  </Panel>
</Collapse>

It renders and operates as expected, but I get a React warning:

Warning: Unknown props 'header', 'isActive', 'prefixCls', 'openAnimation', 'onItemClick' on

tag. Remove these props from the element. For details, see https://fb.me/react-unknown-prop

The error goes away when I only use Panels as children in the Collapse component. But my project design requires that the accordion operate as one accordion even though there are some elements that are in between the accordion panels. Not a high priority as it renders and operates as expected, just thought the warning message should be reported.

Provide a way to provide style to CollapsePanel

Hello

My use case is that I want to hide a Panel depending on a variable.

It would be great to be able to do one of following :

<Panel hide={ true }>
 ...
</Panel>

or

<Panel style={ {display: "none"} }>
 ...
</Panel>

Best regards

Dynamically show and hide panels

I've got a scenario where I need to be able to hide and show panels dynamically. It looks like the way your code works, even if I pass a "null" component into the collapse component as a child, it will still attempt to render a panel from that. Is there a way where I can pass all child vars into the Collapse component, but have it not render null components? Or is there a way on the panels where I can tell a panel not to render?

Thanks!

Hide arrow with showArrow={ false } doesn't work -- fix

This is a note someone who may have this problem in the future

If you import like this:
import Collapse, { Panel } from 'rc-collapse'
import 'rc-collapse/assets/index.css' // use the css in npm module

this won't work:

        <Panel
          showArrow={ false }
          header={ ... }
        >

But Collapse.Panel does work

        <Collapse.Panel
          showArrow={ false }
          header={ ... }
        >

EDIT: actually not sure what's going on...

EDIT: OK, never mind, trying to be helpful but it was my own class that changed the header

Suggestion: multiline headers

In case header is wider than collapse box the rest of header will simply overflow. Perhaps an option to wrap lines or hide overflow?

Can only open, not close a panel

Clicking on the panel header opens it, but clicking on it again it flashes closed for a moment and then re-opens. I would expect it to toggle

        <Collapse>
          <Panel header='Output'>
            <DataGrid idProperty="index" dataSource={tableData} columns={columns} />
          </Panel>
        </Collapse>

There is only one panel in this example, but it happens even if I add another panel. This is under Bootstrap 4.

Not showing arrow

In the default configuration, or with showArrow=true, I'm not seeing an arrow.

        <Collapse>
          <Panel header='Output'>
            <DataGrid idProperty="index" dataSource={tableData} columns={columns} />
          </Panel>
        </Collapse>

This is using Bootstrap 4, if that makes a difference.

ChangeRequest: rc-collapse does not unmount children.

There is a need do determine, if current PanelContent visible or active in it's children.
There are three methods to perform this:

  1. Give PanelContent children isActive property.
  2. Put active panel in modern react context.
  3. Simply remove rendering of component and make user rely on componentWillMount, componentDidUnmount functions to track panels state.

Here is code snippet: render function of PanelContent:

 render() {
    this._isActived = this._isActived || this.props.isActive;
    if (!this._isActived) {
      return null;
    }
    const { prefixCls, isActive, children } = this.props;
    const contentCls = classnames({
      [`${prefixCls}-content`]: true,
      [`${prefixCls}-content-active`]: isActive,
      [`${prefixCls}-content-inactive`]: !isActive,
    });

    return (
      <div
        className={contentCls}
        role="tabpanel"
      >
        {isActive?<div className={`${prefixCls}-content-box`}>{children}</div>: null}

      </div>
    );
  },

In my humble opinion this change is trivial, does not breaks functionality or rc-collapse, and does not breaks user expectations about componentWillMount, componentDidUnmount behaviour.

Server-side rendering issues

Hey, rc-collapse seems to have issues with server side rendering, because of rc-animate:

client.js:4 Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
 (client) .$rc_animate_1460040782855"><div class="
 (server) .$rc_animate_1460040116046"><div class="

Any way to fix it?

import Accordion from 'rc-accordion' 时报错

.//rc-accordion/src/index.js
Module not found: Error: Cannot resolve 'file' or 'directory' ./Accordion in /Volumes/ZBMOBI/React/ReactWebPackDemo/node_modules/rc-accordion/src
resolve file
/Volumes/ZBMOBI/React/ReactWebPackDemo/node_modules/rc-accordion/src/Accordion doesn't exist
/Volumes/ZBMOBI/React/ReactWebPackDemo/node_modules/rc-accordion/src/Accordion.js doesn't exist
resolve directory
/Volumes/ZBMOBI/React/ReactWebPackDemo/node_modules/rc-accordion/src/Accordion/package.json doesn't exist (directory description file)
/Volumes/ZBMOBI/React/ReactWebPackDemo/node_modules/rc-accordion/src/Accordion doesn't exist (directory default file)
[/Volumes/ZBMOBI/React/ReactWebPackDemo/node_modules/rc-accordion/src/Accordion]
[/Volumes/ZBMOBI/React/ReactWebPackDemo/node_modules/rc-accordion/src/Accordion.js]
@ ./
/rc-accordion/src/index.js 2:17-39

collpase 如何手动通过js设置activeKey?

在props里面设置activeKey可以实现多个collapse-item的切换:

<Collapse accordion activeKey="1">
   ...
</Collapse>

但是如何通过js手动设置activeKey,比如

 this.refs.collapse.setState({
    activeKey: 4
 })

类似的?

Header prop for Panel component doesn't return React elements

When I put jsx in the header prop for the Panel component, the component renders [Object, Object] in the jsx's place:

<Panel header={`City ${<span>selected</span>}`} key='1'>
  <div className='fltr-group'>
    ...
  </div>
</Panel>

I would expect 'City selected' to be rendered with some styles applied to the word selected, but all I get back is 'City [Object, Object]'

Is there something I'm forgetting to do?

Suggestion: ESLint warning at Panel className prop

Due to recent changes to ESLint react rules, having a component with a prop named className results in a warning Prop 'className' is forbidden on Components react/forbid-component-props.

It's obvious that having className passed down to the actual DOM element is a valid workflow, thus it's only a warning, but results in it being confusing.

This is the rule description: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/forbid-component-props.md

Opinions on allowing inline-styles passed in through props

Hello, I am hoping to make modifications to Collapse and Panel to allow developers to pass in inline-styles via props. I see that CSS styles are currently being generated using LESS and I was wondering if inline-styles have been considered in the past. If there are no objections, I would be happy to start working on it. Thanks!

**edit: I realize this can be accomplished via the custom className, but it is often easier to be able to directly inject inline-styles.

prefixCls undocumented?

There's an immensely useful prop on Container called prefixCls. It's not in any documentation. Is it safe to use this?

panel collapse wont toggle

I have react js app with rc-collapse. I think I built it right. I am managing the state of the activeKey with the onChange handler and seems ok. But the panels wont close, they do open onclick but wont close.

renderAccordion(about, videos, gallery) {
    return (
        <Collapse 
            accordion={false}
            onChange={this.onAccordionChange.bind(this)}
            activeKey={this.state.activeKey}
        >
            <Panel header="about" key={'about'} >{about}</Panel>
            <Panel header="gallery" key={'photos'} >{this.renderPhotos(gallery)}</Panel>
            <Panel header="video" key={'video'} >{this.renderVideo(videos)}</Panel>
            <Panel header="contact" key={'contact'} >contact us</Panel>
            <Panel header="share" key={'share'} >
                <a href={`whatsapp://send?text=Take a look at my business card: http://react-js-api.herokuapp.com/${this.props.params.id}`} className="wa_btn wa_btn_s">Share</a>
            </Panel>
        </Collapse>
    );
}

managing the state on panel click:

onAccordionChange(activeKey) {
        this.setState({ activeKey });
    }

initialzing the state:

constructor(props) {
      super(props);

      this.state = { activeKey: [] };
    }

When I console.log the activeKey state I get the correct answer - each click on a panel changes the state from active to not active. But the panel isn't closing.

license in package.json

Hello,

Think you may have a typo in your package file.

"license": "MIT",
https://github.com/nkbt/react-collapse/blob/master/package.json

"licenses": "MIT",
https://github.com/react-component/collapse/blob/master/package.json

Tried to add your npm package as a webjar on http://www.webjars.org/npm.
(Add a new npm webjar button)

And got the following error.

Failed! All attempts to determine a license have been exhausted. 
The bower.json did not contain a spec-compliant license definition 
and the license could not be determined by trolling through the GitHub repo. 
This problem will likely need to be resolved by working with the library maintainers directly. 
If you feel you have reached this failure in error, please file an issue: https://github.com/webjars/webjars/issues  

Determined Artifact Name: rc-collapse Starting Deploy

Dynamic rendering of Panel Content during run time.

Is it possible to render a component inside the Panel during run-time in accordion mode.
Use case, when a Panel is opened, need to fetch some data asynchronously and render a component inside the Panel and when any other Panel is opened, the previously rendered component should also unmounted.

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.