import "./index.css"; import React, { Component } from "react"; class Accordion extends Component { static defaultProps = { onChange: () => {}, statusIconsComponents: { opened: "▲", closed: "▼" }, allowMultipleExpand: true }; state = { activeIndexes: [] }; updateIndexes = (index, callback) => { const { allowMultipleExpand, onChange } = this.props; this.setState(prevState => { let activeIndexes; let isOpen = false; if (prevState.activeIndexes.includes(index)) { activeIndexes = allowMultipleExpand ? prevState.activeIndexes.filter( currentIndex => currentIndex !== index ) : []; } else { isOpen = true; activeIndexes = allowMultipleExpand ? prevState.activeIndexes.concat(index) : [index]; } callback(isOpen); onChange(activeIndexes); return { activeIndexes }; }); }; render() { const children = React.Children.map(this.props.children, (child, index) => { const isActive = this.state.activeIndexes.includes(index); return React.cloneElement(child, { isActive, statusIcon: this.props.statusIconsComponents[ isActive ? "opened" : "closed" ], onSelect: onSelectCallback => this.updateIndexes(index, onSelectCallback) }); }); return