Search code examples
javascriptreactjsmodal-dialogreact-modal

React - call parent method in child component after passing it


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


Solution

  • 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>