css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              html {
 overflow-y: scroll;
}

abbr[title] {
  display: inline-block;
  text-decoration: none;
}

.container {
  max-width: 42rem;
  padding: 2rem;
  margin: 0 auto;
  
  & &__title {
    font-size: 1.5rem;
    margin-bottom: 3rem;
  }
}

.accordionList {
  
  & &__list {
    padding: 0;
    list-style: none;
  }

  & &__item + &__item {
    border-top-width: 0;
  }

  & &__buttons {
    margin-bottom: 2rem;
  }
  
  & &__item + &__buttons {
    margin-top: 2rem;
    margin-bottom: 0;
  }

  & &__button {
    min-width: 6em;
    padding: .4em .8em;
    border: 0;
    border-radius: .2em;
    background-color: midnightblue;
    color: #fff;
  }
  
  & &__button + &__button {
    margin-left: 1em;
  }
}

.accordion {
  $transitionDuration: .2s;
  position: relative;
  overflow: hidden;
  border: .25em solid currentColor;
  color: midnightblue;
    
  & &__header {
    display: block;
    position: relative;
    margin: 0;
    background-color: #fff;
    font-size: 1rem;
    padding: 1em;
    transition: background-color $transitionDuration ease;
    
    &:hover,
    &:focus {
      text-decoration: underline;
      background-color: lighten(midnightblue, 70%);
    }
    
    &[aria-expanded="true"] {
      background-color: lighten(midnightblue, 65%);
    }

    &::before {
      content: "";
      box-sizing: border-box;
      display: inline-block;
      border-color: transparent;
      border-width: .4em .6em;
      border-style: solid;
      border-left-color: midnightblue;
      line-height: 1;
      transform-origin: 25% 50%;
      transition: transform $transitionDuration ease-out;
    }

    &[aria-expanded="true"]::before {
      transform-origin: 25% 50%;
      transform: rotate(90deg);
    }
  }
  
  & &__panel {
    box-sizing: border-box;
    height: 0;
    overflow: hidden;
    margin: -2em 0;
    padding: 3em 1em;
    visibility: hidden;
    transition: padding $transitionDuration ease-out;
  }
  
  & &__title:hover &__panel {
    will-change: padding;
  }

  & &__panel[aria-hidden="true"] {
    margin: 0;
    padding: 0 1em;
    transition-duration: $transitionDuration;
  }

  & &__panel > *:first-child {
    margin-top: 0;
  }

  & &__panel > *:last-child {
    margin-bottom: 0;
  }

  // for expanded accordion in closed accordion can't be focused
  & &__panel[aria-hidden="true"] * {
    visibility: hidden;
  }
}
            
          
!
            
              const KEYCODE_ENTER  = 13;
const KEYCODE_SPACE  = 32; 
const KEYCODE_LEFT   = 37;
const KEYCODE_UP     = 38;
const KEYCODE_RIGHT  = 39;
const KEYCODE_DOWN   = 40;

class AccordionList extends React.Component {
  
  constructor(props) {
    super(props);

    // 開閉の状態は AccordionList が Bool の値を配列で持つ。
    let items = [];
    
    // AccordionList の子の Accordion の数によって state の初期化方法を変える
    if(Array.isArray(this.props.children)) {
        this.props.children.forEach((child, i) => {
        items[i] = child.props.expanded === undefined ? false : child.props.expanded;
      });
    } else {
      items.push(this.props.expanded === undefined ? false : child.props.expanded);
    }

    // AccordionList から Accordion のフォーカスも管理する
    let focusItems = new Array(this.props.children.length);
    focusItems.fill(false);

    this.state = {
      expandsItems: items,
      focusItems: focusItems
    }
  }
  
  // すべて開く処理
  expandsAllItems() {
    this.setState({
      expandsItems: this.state.expandsItems.map(() => {
        return true;
      })
    });
  }
  
  // すべて閉じる処理
  closeAllItems() {
    this.setState({
      expandsItems: this.state.expandsItems.map(() => {
        return false;
      })
    });
  }
  
  // 渡された index の 表示状態をトグル
  handleExpandsItem(i) {
    let items = this.state.expandsItems;
    items[i] = items[i] === false ? true : false;
    this.setState({
      expandsItems: items
    });
  }
  
  // focus を反映したら状態をリセットする。
  resetFocusItem() {
    this.setState({
      focusItems: this.state.focusItems.map(() => {
          return false;
        })
    })
  }
  
  // 受け取った index と KeyDownイベントからパネルのトグル or フォーカスを移動
  handleFocusItem(i, e) {
    switch(e.keyCode) {
      case KEYCODE_LEFT:
      case KEYCODE_UP:
        e.preventDefault();
        if(i !== 0) {
          this.setState({
            focusItems: this.state.focusItems.map((items, j) => {
                return i - 1 === j ? true : false;
              })
          }, () => {
            this.resetFocusItem();
          });
        }
        break;
      case KEYCODE_DOWN:
      case KEYCODE_RIGHT:
        e.preventDefault();
        if(i < this.state.expandsItems.length - 1) {
          this.setState({
            focusItems: this.state.focusItems.map((items, j) => {
                return i + 1 === j ? true : false;
              })
          }, () => {
            this.resetFocusItem();
          });
        }
        break;
      case KEYCODE_ENTER:
      case KEYCODE_SPACE:
        e.preventDefault();
        this.handleExpandsItem(i)
        break;
      default:
        break;
    }
  }
  
  render() {
    let items = [];
    let buttons;

    if(this.state.expandsItems.length < 2) {
      items.push(this.props.children);
    } else {
      items = this.props.children;

      if(this.props.allButton === undefined ? true : this.props.allButton) {

        // 子要素の id を空白区切りでまとめた ID 参照リストを作成
        const buttonControlItems = this.props.children.map((child) => {
          return child.props.id;
        }).join(' ');

        buttons = <div className={this.props.className + '__buttons'} role="toolbar">
            <button type="button"
              className={this.props.className + '__button'}
              onClick={this.expandsAllItems.bind(this)}
              aria-controls={buttonControlItems}>All Expand
            </button>
            <button type="button"
              className={this.props.className + '__button'}
              onClick={this.closeAllItems.bind(this)}
              aria-controls={buttonControlItems}>All Close
            </button>
          </div>;
        }
    }

    items = items.map((child, i) => {
      return (
        <Accordion
          label={child.props.label}
          id={child.props.id}
          dataNum={i}
          ref={this.props.id + i}
          key={this.props.id + i}
          focus={this.state.focusItems[i]}
          className={this.props.className + '__item'}
          expanded={this.state.expandsItems[i]}
          onButtonClick={this.handleExpandsItem.bind(this)}
          onButtonKeyDown={this.handleFocusItem.bind(this)}>
          {child.props.children}
        </Accordion>
      );
    });

    return (
      <div className={this.props.className} id={this.props.id}>
        {buttons}
        <ul className={this.props.className + '__list'} role="tablist" aria-multiselectable="true">
        {items}
        </ul>
      </div>
    );
  }
}

class Accordion extends React.Component {
  
  constructor(props) {
    super(props);
  };

  handleExpandItem(i) {
    this.props.onButtonClick(i);
  }

  handleKeyExpandItem(i, e) {
    this.props.onButtonKeyDown(i, e);
  }
  
  componentDidUpdate() {
    if(this.props.focus) {
      this.refs["accordion__header"].focus();
    }
  }
  

  render() {
    const viewStyle = {
      height: "auto",
      visibility: "visible"
    };
    const classBlockName = "accordion";

    return (
      <li className={this.props.className + ' ' + classBlockName} role="presentation">
        <a className={classBlockName + "__header"}
          ref={classBlockName + "__header"}
          onClick={this.handleExpandItem.bind(this, this.props.dataNum)}
          onKeyDown={this.handleKeyExpandItem.bind(this, this.props.dataNum)}
          role="tab"
          aria-expanded={this.props.expanded}
          aria-selected={this.props.expanded}
          aria-controls={this.props.id}
          tabIndex="0">{this.props.label}
        </a>
        <div className={classBlockName + "__panel"}
          id={this.props.id}
          aria-hidden={!this.props.expanded}
          style={this.props.expanded ? viewStyle : null}>
          {this.props.children}
        </div>
      </li>
    );
  }
}

class Container extends React.Component {
  render() {
    let text = <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Facere aut odit totam quas, doloribus, <a href="#dummy">laboriosam</a> eius deleniti, molestias doloremque debitis nisi quod eaque saepe similique ut voluptas ea neque dolores!</p>;

    return(
      <div className="container">
      <h1 className="container__title">Collapsible(Accordion) UI with React &amp; <abbr title="Web Accessibility Initiative - Accessible Rich Internet Applications">WAI-ARIA</abbr> role=&quot;tablist&quot;</h1>

      <AccordionList className="accordionList" allButton={true} id="AccordionList1" key="AccordionList1">
        <Accordion label="Accordion1" id="Accordion1" expanded={false}>
          {text}
        </Accordion>
        <Accordion label="Accordion2" id="Accordion2" expanded={false}>
          {text}
        </Accordion>
        <Accordion label="Accordion3" id="Accordion3" expanded={true}>
          {text}
          <AccordionList className="accordionList" allButton={false}>
            <Accordion label="Accordion in Accordion" id="Accordion3-1" key="Accordion3-1" expanded={false}>
              {text}
            </Accordion>
          </AccordionList>
        </Accordion>
      </AccordionList>
      </div>
    );
  }
}

ReactDOM.render(<Container />, document.getElementById('app'));
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console