How do I close a dialog in another component from Material-UI in React?

Viewed 9179

I have a modal that have a component inside. I want to close the modal from that component.

I got a component that have:

<Modal open={modalClients} onClose={handleCloseModalClients}>
   <div className={classes.paper}>
      <ClientsTable />
   </div>
</Modal>

It is possible to close the modal inside ClientsTable?

3 Answers

It looks like handleCloseModalClients is what closes the modal, so you should just need to pass it into ClientsTable and call it somehow. For example, if you have a button in ClientsTable:

<Modal open={modalClients} onClose={handleCloseModalClients}>
   <div className={classes.paper}>
      <ClientsTable onCloseModal={handleCloseModalClients} />
   </div>
</Modal>

const ClientsTable = (props) => (
  // Not sure what the inside of ClientsTable looks like, but
  // it should have something you can attach the handler to:
  <div>
    <button onClick={props.onCloseModal}>Close Modal</button>
  </div>
)

According to https://material-ui.com/api/modal/ , you can control opening and closing the modal through the open prop in the component.

Therefore, you can define a state variable in your modal component state = { open: false }

and a function to close it closeModal = () => { this.setState({ open: false }); }

and you can pass closeModal function as a prop to the child component inside the modal

<ClientsTable closeModal={closeModal} />. Then you can trigger the closeModal function wherever you want inside the <ClientsTable> component.

Here is an example: https://codesandbox.io/s/material-demo-7nc1p

As you are already using open={modalClients}, and assuming your modalClients must be in a state. You can set this state to false to close the modal from your ClientsTable component like,

const ClientsTable = props => (
  <div>
    <button onClick={props.hideModal}>Hide</button>
  </div>
);

And your modal should look like,

<Modal open={this.state.modalClients}>
    <div className="">
       <ClientsTable hideModal={() => this.setState({ modalClients: false })} />
    </div>
</Modal>

Demo

Related