How to close semantic ui modal in another react component?

user3142695 picture user3142695 · Feb 21, 2017 · Viewed 9.8k times · Source

In my main component I can open a modal by clicking on an icon. The content of the modal is a separate component, which is calling a method. If the method call is successful, I want to close the modal. But how can I do this?

Main component

class Example extends Component {
    constructor(props) {
        super(props)
        this.state = {}
    }

    render() {
        return (
            <div>
                <Modal trigger={ <Icon name='tags' /> } >
                    <Modal.Header>
                        <div>
                            <Header floated='left'>Title</Header>
                            <Button floated='right'>A Button</Button>
                        </div>
                    </Modal.Header>
                    <Modal.Content>

                        <ModalContent />

                    </Modal.Content>
                </Modal>
            </div>
        )
    }
}

Modal content

class ModalContent extends Component {
    constructor(props) {
        super(props)
        this.state = {}
    }

    handleClick() {
        method.call(
            { param },
            (error, result) => {
                if (result) {
                    // Now close the modal
                }
            }
        );
    }

    render() {
        return (
            <Button onClick={this.handleClick} content='Save' />
        )
    }
}

Answer

Deividas Karzinauskas picture Deividas Karzinauskas · Feb 21, 2017

You should add an onClose property to <Modal> element. See example below:

<Modal
    trigger={<Button onClick={this.handleOpen}>Show Modal</Button>}
    open={this.state.modalOpen}
    onClose={this.handleClose}
  >

Then you can add onClose function to a button in your modal. Full example from the docs: https://react.semantic-ui.com/modules/modal#modal-example-controlled