Kavya nagendra
Kavya nagendra

Reputation: 93

I have my modal component in a different file and I'm trying to open it from another component

BuySectionItem.js

    class BuySectionItem extends React.PureComponent {
        constructor( props ) {
            super( props );

            this.state = {
                modalIsOpen:        false,
            }
            this.toggleTicketModal = this.toggleTicketModal.bind( this );
        }

        toggleTicketModal = () => {
            this.setState( { modalIsOpen: ! this.state.modalIsOpen } );
        }

        componentDidMount() {
            // this.setActivePrice();
        }

        outputBuyButton( offer ) {
            // Universe ID override is present.

                return  <Button text="Buy Ticket" type="green-gradient" onClick={ this.toggleTicketModal }/>

            return null;
        }

        render() {
            <div>
                {this.state.modalIsOpen &&
                    <TicketModal isOpen={this.state.modalIsOpen} toggleTicketModal={ this.toggleTicketModal } />
                }
            </div>;
        }
    }

    export default BuySectionItem;

TicketModal.js

    import React from 'react';
    import Modal from 'react-modal';
    import PropTypes from 'prop-types';

    const customStyles = {
        content: {
            top:         '50%',
            left:        '50%',
            right:       'auto',
            bottom:      'auto',
            marginRight: '-50%',
            transform:   'translate(-50%, -50%)',
        },
    };

    Modal.setAppElement( 'body' )

    class TicketModal extends React.Component {

componentDidMount() {
        this.handleKeyEvents();
    }

    componentWillUnmount() {
        this.removeKeyHandler();
    }

    /**
     * Watch for the escape key when the modal is open to allow users to escape from the modal.
     */
    handleKeyEvents() {
        const handleKeyDown = event => {
            if ( event.keyCode === 27 ) {
                this.props.toggleTicketModal( event );
            }
        };

        /*
         * Attach our event listener to the window.
         */
        window.addEventListener( 'keydown', handleKeyDown );

        /*
         * Cancel the key event handling, and remove
         */
        this.removeKeyHandler = () => {
            window.removeEventListener( 'keydown', handleKeyDown );
        };
    }
    render() {
            const {
                isOpen,
                // pending,
                toggleTicketModal,
            } = this.props;
            return (
          <Modal
          isOpen={isOpen}
          onRequestClose={toggleTicketModal()}
          style={customStyles}
          contentLabel="Meal Modal"
          >
            <div className="modal-wrapper">
              <div className="container text-center">
                <h1>Hello</h1>
                <h2>ID of this modal is 100</h2>
                <h3>This is an awesome modal.</h3>
                <button onClick={toggleTicketModal()}>close</button>
              </div>
            </div>
          </Modal>
            )
        }
    }
    TicketModal.propTypes = {
        pending:           PropTypes.bool,
        toggleTicketModal: PropTypes.func,
        isOpen:            PropTypes.bool,
    };

    export default TicketModal;


As you can see I am trying to open the ticket modal component from the `buysectionitem` component on a button Click.

But for some reason the Modal doesn't seem to be opening.

When I kept a break point I see that the `togglemodal` function is being called but doesn't open at all.

I added some more code as I need guidance with the handle key events as well. This key event which was supposed to remove the modal from the screen when I click escape which doesn't seem to be working.

Upvotes: 2

Views: 2687

Answers (3)

akhtarvahid
akhtarvahid

Reputation: 9779

Optimized code

class BuySectionItem extends React.Component {
  constructor() {
    super();
    this.state = {
      showModal: false
    };
  }

  handleOpenClose = () => {
    this.setState(prev => ({ showModal: !prev.showModal }));
  };
  render() {
    return (
      <div>
        <button onClick={this.handleOpenClose}>Trigger Modal</button>
        <Modal
          isOpen={this.state.showModal}
          contentLabel="Minimal Modal Example"
        >
          <TicketModal handleOpenClose={this.handleOpenClose} />
        </Modal>
      </div>
    );
  }
}
class TicketModal extends React.Component {
  render() {
    const { handleOpenClose } = this.props;
    return (
      <div>
        <button onClick={handleOpenClose}>Close Modal</button>
        <hr />
        <p>Welcome to opened model</p>
      </div>
    );
  }
}

Live demo

Upvotes: 2

Ayyappa Gollu
Ayyappa Gollu

Reputation: 966

there are many mistakes in your code. button onclick handler in modal should be like following,

    <button onClick={toggleTicketModal}>close</button>

also you don't have to do same handling while closing the modal, following is redundant inside Modal props

onRequestClose={toggleTicketModal}

also main container in your case BuySectionItem.js has few issues. 1.there is no return in render method. 2.conditional rendering is not done correctly, you are never calling outPutBuyButton based on modalIsOpen state 3. you have used name "isModalOpen" instead of "modalIsOPen" , bad typo.

here's working code. modify as per your needs.

https://codesandbox.io/s/gracious-hopper-vmerd

Upvotes: 1

warmachine
warmachine

Reputation: 376

you are calling the toggleTicketModal function when the TicketModal renders,call it like this

<button onClick={()=>toggleTicketModal()}>close</button>

this will do.

Upvotes: 1

Related Questions