Ackman
Ackman

Reputation: 1592

How to pass props to a children object? children will only have a button or a text

export const PopOver = ({
  children, -----------------------------------------> I get children
  headerText,
  bodyText,
  hasHeader,
  hasBody,
  hasFooter,
  cancelButtonText,
  okButtonText,
  hasCloseButton,
  onOkPress,
  onCancelPress,
  ...rest
}: PopoverProps): JSX.Element => {
  return (
    <Popover
      trigger={(triggerProps) => {
        return <Button {...triggerProps}>Trigger</Button>; //How do I pass trigger props to the children I get???
      }}
      {...rest}
    >

In the code I have mentioned above, I want to return children (this.props.children) instead of the button to make it more generic. something to the equivalent of:

return (
    <Popover
      trigger={(triggerProps) => {
        return <child {...triggerProps}>Trigger</child>;
      }}
      {...rest}
    >

Upvotes: 1

Views: 104

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

Try this:

<Popover
  trigger={triggerProps => 
    React.Children.map(children, child =>
      React.isValidElement(child) 
        ? React.cloneElement(child, { ...triggerProps }) 
        : child
    )
  }
  {...rest}
/>

References:

https://reactjs.org/docs/react-api.html#reactchildren

https://reactjs.org/docs/react-api.html#cloneelement

Upvotes: 1

Related Questions