Skip to content

Instantly share code, notes, and snippets.

@lai32290
Created September 23, 2020 21:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lai32290/2f98f6b98099e42cfd0dfcce215436fd to your computer and use it in GitHub Desktop.
Save lai32290/2f98f6b98099e42cfd0dfcce215436fd to your computer and use it in GitHub Desktop.
class Accordion extends React.Component {
- state = {openIndex: 0}
- setOpenIndex = openIndex => this.setState({openIndex})
+ state = {openIndexes: [0]}
+ setOpenIndex = openIndex => this.setState({openIndexes: [openIndex]})
render() {
- const {openIndex} = this.state
+ const {openIndexes} = this.state
return (
<div>
{this.props.items.map((item, index) => (
<>
<button onClick={() => this.setOpenIndex(index)}>
{item.title}
</button>
- {index === openIndex ? (
+ {openIndexes.includes(index) ? (
<AccordionContents>{item.contents}</AccordionContents>
) : null}
</>
))}
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment