Skip to content

Instantly share code, notes, and snippets.

@DZuz14
Created July 17, 2020 20:21
Show Gist options
  • Save DZuz14/6bb6912388e3135f09316702c73cc8a2 to your computer and use it in GitHub Desktop.
Save DZuz14/6bb6912388e3135f09316702c73cc8a2 to your computer and use it in GitHub Desktop.
Acccordion Finished
import React, { useState } from 'react'
import Collapsed from './Collapsed'
import Expanded from './Expanded'
/**
* @function Accordion
*/
const Accordion = ({ children, initial }) => {
const [open, setOpen] = useState(initial)
const handleOpen = (e) => {
const id = e.target.getAttribute('data-id')
id === open ? setOpen('') : setOpen(id)
}
return (
<div>
{React.Children.map(children, child => {
const id = child.props.children[0].props.id
const collapsed = React.cloneElement(child.props.children[0], {
handleOpen
})
const expanded = child.props.children[1]
return (
<div>
{collapsed}
{id === open && expanded}
</div>
)
})}
</div>
)
}
Accordion.Collapsed = Collapsed
Accordion.Expanded = Expanded
Accordion.Item = ({ children }) => children
export default Accordion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment