1

I am trying to create a modal component in which i pass the content of the given modal as a child.

< GGModal buttonLabel="Login" content={
    <LoginScreen
        setToken={setToken}
        token={token}
        setEmail={setEmail}
        email={email}
     />} />

and then in GGModal i display the content like this:

           <Modal
                isOpen={modalIsOpen}
                onRequestClose={closeModal}
                style={{
                    overlay: { zIndex: 2 },
                }}
            >
                {content}
            </Modal>

I would like to call a method defined in GGModal (closeModal) from any given content i pass to it. However I don't know how to pass props to the {content}

Is it possible?

Thanks

2 Answers2

0

use children prop instead of defining your custom prop. React is configured to take children prop as any jsx element passed as child. Make sure to provide children as last prop in the arguments.

export default function GGModal({buttonLabel, children}){
       <Modal
            isOpen={modalIsOpen}
            onRequestClose={closeModal}
            style={{
                overlay: { zIndex: 2 },
            }}
        >
            {children}
        </Modal>
 }
0

You have to clone the children in order to do it.

export default GGModal = ({buttonLabel, children}) => {
      const parentFunction => 'parent function';
       <Modal
            isOpen={modalIsOpen}
            onRequestClose={closeModal}
            style={{
                overlay: { zIndex: 2 },
            }}
        >
            {React.cloneElement(children, { parentFuntion })}
        </Modal>
 }


<GGModal buttonLabel='Login' /> <LoginScreen
        setToken={setToken}
        token={token}
        setEmail={setEmail}
        email={email}
     /> </GGModal>
Janitha Tennakoon
  • 856
  • 11
  • 40
  • {React.cloneElement(children, { parentFuntion })} did the trick! is there any drawback from cloning the element? Marked as solution – Marco Gabaglio Aug 30 '21 at 16:55