overleaf/services/web/frontend/js/shared/components/controlled-dropdown.tsx
Alf Eaton e95ad3e71b Tidy up shared React components (#9509)
GitOrigin-RevId: b8029b65c95ccdac89587d484e2599e25fe44302
2023-01-06 09:03:47 +00:00

34 lines
909 B
TypeScript

import { Children, cloneElement, type FC, isValidElement } from 'react'
import { Dropdown, DropdownProps } from 'react-bootstrap'
import useDropdown from '../hooks/use-dropdown'
const ControlledDropdown: FC<
DropdownProps & { defaultOpen?: boolean }
> = props => {
const dropdownProps = useDropdown(Boolean(props.defaultOpen))
return (
<Dropdown {...props} {...dropdownProps}>
{Children.map(props.children, child => {
if (!isValidElement(child)) {
return child
}
// Dropdown.Menu
if ('open' in child.props) {
return cloneElement(child, { open: dropdownProps.open })
}
// Overlay
if ('show' in child.props) {
return cloneElement(child, { show: dropdownProps.open })
}
// anything else
return cloneElement(child)
})}
</Dropdown>
)
}
export default ControlledDropdown