I have this Popover HOC component. How can I access closePopover
method in the children? as you can see I have passed it as prop but I have no way to access it in children.
import { useState, useCallback, cloneElement } from 'react'
import { EuiButtonEmpty, EuiPopover } from '@elastic/eui'
const CustomPopover = ({ children }) => {
const [isPopoverOpen, setIsPopoverOpen] = useState(false)
const closePopover = useCallback(() => setIsPopoverOpen(false), [])
const onButtonClick = () => setIsPopoverOpen(isPopoverOpen => !isPopoverOpen)
const button = (
<EuiButtonEmpty
iconType='boxesHorizontal'
iconSide='right'
onClick={onButtonClick}
></EuiButtonEmpty>
)
return (
<div>
<EuiPopover
button={button}
isOpen={isPopoverOpen}
closePopover={closePopover}
>
{cloneElement(children, { closePopover })}
</EuiPopover>
</div>
)
}
export default CustomPopover
I am using it this way:
<CustomPopover>
<div className='flex flex-col space-y-5'>
<button
onClick={() => setSortAsc(true)}
className='hover:bg-slate-100'
>
Sort by Oldest Message
</button>
<button
onClick={() => setSortAsc(false)}
className='hover:bg-slate-100'
>
Sort by Latest Message
</button>
</div>
</CustomPopover>
CodePudding user response:
Using a function as the child might be an approach here, i.e. for popover having
return (
<div>
<EuiPopover
button={button}
isOpen={isPopoverOpen}
closePopover={closePopover}
>
// Pass in an object containing things you want to use when rendering,
// in this case close function
{children({ closePopover })}
</EuiPopover>
</div>
)
Then when using it, have a function as the child:
<CustomPopover>
{props => (
// So here you can access the object you passed into children({...})
<button onClick={props.closePopover}></button>
)}
</CustomPopover>