ReactJS – Open/Close Modal from another component

Hello there,

Open a Modal in the same page is not a big deal, but when you want to separate it in another page of you app to keep more organized, you can use this method below.

The main page, with the open button to Modal will contain the variable with the status of the modal (showModal). And in this same page, a function to change this state (toggleModal).

in the return method of main page, we will send the props with those 2 values:

<Modal isOpen={this.state.showModal} toggle={this.toggleModal} />

The trick: the toggle props will be executed from our Modal page, changing the state of the Modal to true or false. Simple like that.

Main Page:

import React, { Component } from 'react';
import Modal from '../../Components/Modal';

export default class Main extends Component {
    state = {
        showModal: false,
    }

    toggleModal = () => {
        this.setState({ showModal: !this.state.showModal });
    } 

    render(){

        return (
            <div>
                <button 
                    onClick={ this.toggleModal } >
                    Opem Modal
                </button>
                <Modal 
                    isOpen={this.state.showModal} 
                    toggle={this.toggleModal} 
                />
            </div>
        );
    }
}

Modal Page:

import React, { Component } from 'react';
import Modal from 'react-modal';

export default function Modal(props){

    return(
      
        <div className="modal">
            <Modal
                isOpen={ props.isOpen }
                contentLabel="Example Modal" >
                <h1>Modal Screen</h1>
                <button onClick={props.toggle}>close</button>
            </Modal>  
        </div>     
    )
}
ReactJS – Open/Close Modal from another component
Tagged on:                     

Leave a Reply

Your email address will not be published. Required fields are marked *