Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React HOC: how to access props passed by the parent compoent?

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading