270

I'm building an app that needs to show a confirm dialog in some situations.

Let's say I want to remove something, then I'll dispatch an action like deleteSomething(id) so some reducer will catch that event and will fill the dialog reducer in order to show it.

My doubt comes when this dialog submits.

  • How can this component dispatch the proper action according to the first action dispatched?
  • Should the action creator handle this logic?
  • Can we add actions inside the reducer?

edit:

to make it clearer:

deleteThingA(id) => show dialog with Questions => deleteThingARemotely(id)

createThingB(id) => Show dialog with Questions => createThingBRemotely(id)

So I'm trying to reuse the dialog component. Showing/hiding the dialog it's not the problem as this can be easily done in the reducer. What I'm trying to specify is how to dispatch the action from the right side according to the action that starts the flow in the left side.

Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
carlesba
  • 3,106
  • 3
  • 17
  • 16
  • 1
    I think in your case the state of dialog (hide/show) is local. I would choose to use the react state to manage dialog showing/hiding. In this way, the question of "proper action according to the first action" will be gone. – Ming Sep 05 '16 at 05:51

5 Answers5

556

The approach I suggest is a bit verbose but I found it to scale pretty well into complex apps. When you want to show a modal, fire an action describing which modal you'd like to see:

Dispatching an Action to Show the Modal

this.props.dispatch({
  type: 'SHOW_MODAL',
  modalType: 'DELETE_POST',
  modalProps: {
    postId: 42
  }
})

(Strings can be constants of course; I’m using inline strings for simplicity.)

Writing a Reducer to Manage Modal State

Then make sure you have a reducer that just accepts these values:

const initialState = {
  modalType: null,
  modalProps: {}
}

function modal(state = initialState, action) {
  switch (action.type) {
    case 'SHOW_MODAL':
      return {
        modalType: action.modalType,
        modalProps: action.modalProps
      }
    case 'HIDE_MODAL':
      return initialState
    default:
      return state
  }
}

/* .... */

const rootReducer = combineReducers({
  modal,
  /* other reducers */
})

Great! Now, when you dispatch an action, state.modal will update to include the information about the currently visible modal window.

Writing the Root Modal Component

At the root of your component hierarchy, add a <ModalRoot> component that is connected to the Redux store. It will listen to state.modal and display an appropriate modal component, forwarding the props from the state.modal.modalProps.

// These are regular React components we will write soon
import DeletePostModal from './DeletePostModal'
import ConfirmLogoutModal from './ConfirmLogoutModal'

const MODAL_COMPONENTS = {
  'DELETE_POST': DeletePostModal,
  'CONFIRM_LOGOUT': ConfirmLogoutModal,
  /* other modals */
}

const ModalRoot = ({ modalType, modalProps }) => {
  if (!modalType) {
    return <span /> // after React v15 you can return null here
  }

  const SpecificModal = MODAL_COMPONENTS[modalType]
  return <SpecificModal {...modalProps} />
}

export default connect(
  state => state.modal
)(ModalRoot)

What have we done here? ModalRoot reads the current modalType and modalProps from state.modal to which it is connected, and renders a corresponding component such as DeletePostModal or ConfirmLogoutModal. Every modal is a component!

Writing Specific Modal Components

There are no general rules here. They are just React components that can dispatch actions, read something from the store state, and just happen to be modals.

For example, DeletePostModal might look like:

import { deletePost, hideModal } from '../actions'

const DeletePostModal = ({ post, dispatch }) => (
  <div>
    <p>Delete post {post.name}?</p>
    <button onClick={() => {
      dispatch(deletePost(post.id)).then(() => {
        dispatch(hideModal())
      })
    }}>
      Yes
    </button>
    <button onClick={() => dispatch(hideModal())}>
      Nope
    </button>
  </div>
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)

The DeletePostModal is connected to the store so it can display the post title and works like any connected component: it can dispatch actions, including hideModal when it is necessary to hide itself.

Extracting a Presentational Component

It would be awkward to copy-paste the same layout logic for every “specific” modal. But you have components, right? So you can extract a presentational <Modal> component that doesn’t know what particular modals do, but handles how they look.

Then, specific modals such as DeletePostModal can use it for rendering:

import { deletePost, hideModal } from '../actions'
import Modal from './Modal'

const DeletePostModal = ({ post, dispatch }) => (
  <Modal
    dangerText={`Delete post ${post.name}?`}
    onDangerClick={() =>
      dispatch(deletePost(post.id)).then(() => {
        dispatch(hideModal())
      })
    })
  />
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)

It is up to you to come up with a set of props that <Modal> can accept in your application but I would imagine that you might have several kinds of modals (e.g. info modal, confirmation modal, etc), and several styles for them.

Accessibility and Hiding on Click Outside or Escape Key

The last important part about modals is that generally we want to hide them when the user clicks outside or presses Escape.

Instead of giving you advice on implementing this, I suggest that you just don’t implement it yourself. It is hard to get right considering accessibility.

Instead, I would suggest you to use an accessible off-the-shelf modal component such as react-modal. It is completely customizable, you can put anything you want inside of it, but it handles accessibility correctly so that blind people can still use your modal.

You can even wrap react-modal in your own <Modal> that accepts props specific to your applications and generates child buttons or other content. It’s all just components!

Other Approaches

There is more than one way to do it.

Some people don’t like the verbosity of this approach and prefer to have a <Modal> component that they can render right inside their components with a technique called “portals”. Portals let you render a component inside yours while actually it will render at a predetermined place in the DOM, which is very convenient for modals.

In fact react-modal I linked to earlier already does that internally so technically you don’t even need to render it from the top. I still find it nice to decouple the modal I want to show from the component showing it, but you can also use react-modal directly from your components, and skip most of what I wrote above.

I encourage you to consider both approaches, experiment with them, and pick what you find works best for your app and for your team.

Alireza
  • 100,211
  • 27
  • 269
  • 172
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
  • 37
    One thing I'd suggest is having the reducer maintain a list of modals that can be pushed and popped. As silly as it sounds, I've consistently run into situations where designers/product types want me to open a modal from a modal, and it nice to allow users to "go back". – Kyle Feb 26 '16 at 01:46
  • 10
    Yeah, definitely, this is the kind of thing Redux makes easy to build because you can just change your state to be an array. Personally I’ve worked with designers who, on the opposite, wanted modals to be exclusive, so the approach I wrote up solves accidental nesting. But yeah, you can have it both ways. – Dan Abramov Feb 26 '16 at 01:56
  • 4
    In my experience I'd say: if modal is related to a local component (like a delete confirmation modal is related to the delete button), it's simpler to use a portal, else use redux actions. Agree with @Kyle one should be able to open a modal from a modal. It also works by default with portals because they are added in order to document body so portals stack on each others nicely (until you mess everything up with z-index :p) – Sebastien Lorber Feb 26 '16 at 10:45
  • 6
    @DanAbramov, your solution is great, but I have minor problem. Nothing serious. I use Material-ui in project, when closing modal it just shut it off, instead of "playing" fade-away animation. Probably need to do some sort of delay? Or keep every modal there as a list inside of ModalRoot? Suggestions? – gcerar Mar 06 '16 at 21:21
  • @adam-sanderson : Saw your edit suggestion, but you may consider asking the answerer about editing it. – sjsam Apr 24 '16 at 03:26
  • @DanAbramov I've done something along these lines, but I'm not sure if it's the React/Redux way... where would be a good forum to have a quick discussion about it? – The Bearded Llama Jul 22 '16 at 09:25
  • Thanks for taking the time to create this great answer! +1 :) – Philipp Aug 11 '16 at 18:51
  • 8
    Sometimes I want to call certain functions after the modal closes (for example call the functions with the input field values inside the modal). I'd pass these functions as `modalProps` to the action. This violates the rule of keeping the state serializable though. How can I overcome this issue? – chmanie Oct 09 '16 at 20:30
  • 3
    Is there a way to pass in a function from the parent container/compoonent that can be called once the modal is closed? I can call actions from the modal on button presses but I would like a callback when the modal closes that will allow me to execute a function on the parent. Parent loads -> button click dispatches modal -> on confirm on modal dispatches an action and then dispatches hideModal -> parent function in container is called and if confirm was success then the page is redirected.. – Brett Mathe Oct 16 '16 at 21:56
  • 2
    UPDATE: It looks like functions can be passed in props. So now my modal on confirm will falsey check the function passed in and then calls it after the save is successful. – Brett Mathe Oct 16 '16 at 22:20
  • @gcerar I got the same issue. Did you find any solution? – Yoihito Oct 24 '16 at 15:03
  • 1
    @Yoihito I looked the source of MUI and animation is done in about 250ms. I have done hacky way and introduced redux action with setTimeout. Best way to keep this working is to assign ID for every modal. To not accidentally delete too many or first in array. – gcerar Oct 24 '16 at 16:28
  • My 50 cents to `Other Approaches` section: https://github.com/fckt/react-layer-stack - it's all-in-one solution for these kind of problems and everything in between. – fckt Nov 07 '16 at 07:40
  • 2
    Sorry, could someone please explain where `dispatch` comes from in deletePostModal code snippet above? Why it should be in props object when we only passing there `post` property? – dKab Dec 29 '16 at 14:02
  • I have worked out a detailed, tweaked explanation of this solution here: https://codersmind.com/scalable-modals-react-redux/ with a demo repo. – randomKek Feb 17 '17 at 12:26
  • 1
    @DanAbramov what do you do if an action in modal should close current modal and open another? Dispatch two actions or make one action that does both? (like openOnlyModal() instead of closeModal() and openModal() ) – Aurimas Apr 23 '17 at 20:33
  • @DanAbramov This looks great. but what if you want a general modal that takes in the action and dispatch it? for example: a user made some edits to some inputs, now the user wants to perform an action that can change the state but he will loose the changes he maid. you want to pop-up a confirm dialog "Are you sure you don't want to save...". now the problem here is that the action is dynamic (refresh button, route transition, etc..) if the user clicks 'yes' then we need to dispatch that action, if he clicks 'cancel' we need to just hide the modal. so is it OK to pass an action to the dialog? – Sagiv b.g Jul 27 '17 at 20:02
  • @DanAbramov Did @dKab ever get answered? Im also confused about how we are suddenly passing in `dispatch` to `DeletePostModal` but `ModalRoot` is the one passing props to it no? – Azeli Oct 14 '17 at 09:12
  • 1
    One of the best react answers in SO! (oops just notice its Dan Abramov) - Ahhh Not bad Dan! – chenop Nov 13 '17 at 15:15
  • @dKab the connect() function is the one that push the dispatch in the props - probably you have removed the connect. – chenop Nov 14 '17 at 19:02
  • @Sag1v You could provide callbacks (e.g. `handleConfirm`) as props of `modalProps` that would then dispatch new actions for refreshing, routing, etc. – colti Nov 30 '17 at 21:59
  • But i have read that you should not store functions inside the store.How can i manage callbacks i.e onExited etc? – Jan Ciołek Dec 19 '17 at 12:25
  • I'm stuck on the same issue. If I want a generic confirmation dialog, the function that kicks off the dialog needs to be able to determine what happens when it closes. Defining the onClose handler in the dialog component makes this impossible. And passing a callback in the Redux action is wrong, since it's not serializable. How are people doing this? – JW. Mar 27 '18 at 19:39
  • @JanCiołek I see your issue. I don't have a low-effort way of doing this, but it's possible. You can pass some prop in `modalProps` that has some unique uuid of the currently dispatched action, which is then stored in something like `state.modals.open = [id]` and then have your modal dispatch an action that will remove that `id` from the redux store on exit `{type: 'HIDE_MODAL', id}` - or some other action you listen to. You could then pass `removedModals` as a prop to your componenet and trigger a callback when a modal id matches the one you initiated. – oligofren Oct 22 '18 at 08:35
  • @JW. Following up on that comment, maybe it's simply a hint that the initiating component shouldn't rely on knowing then the modal is finished, relying instead on computing its state from other props in the store. Anyway, it seems _possible_. – oligofren Oct 22 '18 at 08:37
  • That's why I follow these legends (eg. @Dan Ambrew) on wherever they are available. – Manish Jangir Oct 27 '18 at 08:18
  • The props passed to the modal are store in the Store. Would it be okay to pass callbacks as props or is that a bad idea? – user1283776 Apr 12 '19 at 14:14
109

Update: React 16.0 introduced portals through ReactDOM.createPortal link

Update: next versions of React (Fiber: probably 16 or 17) will include a method to create portals: ReactDOM.unstable_createPortal() link


Use portals

Dan Abramov answer first part is fine, but involves a lot of boilerplate. As he said, you can also use portals. I'll expand a bit on that idea.

The advantage of a portal is that the popup and the button remain very close into the React tree, with very simple parent/child communication using props: you can easily handle async actions with portals, or let the parent customize the portal.

What is a portal?

A portal permits you to render directly inside document.body an element that is deeply nested in your React tree.

The idea is that for example you render into body the following React tree:

<div className="layout">
  <div className="outside-portal">
    <Portal>
      <div className="inside-portal">
        PortalContent
      </div>
    </Portal>
  </div>
</div>

And you get as output:

<body>
  <div class="layout">
    <div class="outside-portal">
    </div>
  </div>
  <div class="inside-portal">
    PortalContent
  </div>
</body>

The inside-portal node has been translated inside <body>, instead of its normal, deeply-nested place.

When to use a portal

A portal is particularly helpful for displaying elements that should go on top of your existing React components: popups, dropdowns, suggestions, hotspots

Why use a portal

No z-index problems anymore: a portal permits you to render to <body>. If you want to display a popup or dropdown, this is a really nice idea if you don't want to have to fight against z-index problems. The portal elements get added do document.body in mount order, which means that unless you play with z-index, the default behavior will be to stack portals on top of each others, in mounting order. In practice, it means that you can safely open a popup from inside another popup, and be sure that the 2nd popup will be displayed on top of the first, without having to even think about z-index.

In practice

Most simple: use local React state: if you think, for a simple delete confirmation popup, it's not worth to have the Redux boilerplate, then you can use a portal and it greatly simplifies your code. For such a use case, where the interaction is very local and is actually quite an implementation detail, do you really care about hot-reloading, time-traveling, action logging and all the benefits Redux brings you? Personally, I don't and use local state in this case. The code becomes as simple as:

class DeleteButton extends React.Component {
  static propTypes = {
    onDelete: PropTypes.func.isRequired,
  };

  state = { confirmationPopup: false };

  open = () => {
    this.setState({ confirmationPopup: true });
  };

  close = () => {
    this.setState({ confirmationPopup: false });
  };

  render() {
    return (
      <div className="delete-button">
        <div onClick={() => this.open()}>Delete</div>
        {this.state.confirmationPopup && (
          <Portal>
            <DeleteConfirmationPopup
              onCancel={() => this.close()}
              onConfirm={() => {
                this.close();
                this.props.onDelete();
              }}
            />
          </Portal>
        )}
      </div>
    );
  }
}

Simple: you can still use Redux state: if you really want to, you can still use connect to choose whether or not the DeleteConfirmationPopup is shown or not. As the portal remains deeply nested in your React tree, it is very simple to customize the behavior of this portal because your parent can pass props to the portal. If you don't use portals, you usually have to render your popups at the top of your React tree for z-index reasons, and usually have to think about things like "how do I customize the generic DeleteConfirmationPopup I built according to the use case". And usually you'll find quite hacky solutions to this problem, like dispatching an action that contains nested confirm/cancel actions, a translation bundle key, or even worse, a render function (or something else unserializable). You don't have to do that with portals, and can just pass regular props, since DeleteConfirmationPopup is just a child of the DeleteButton

Conclusion

Portals are very useful to simplify your code. I couldn't do without them anymore.

Note that portal implementations can also help you with other useful features like:

  • Accessibility
  • Espace shortcuts to close the portal
  • Handle outside click (close portal or not)
  • Handle link click (close portal or not)
  • React Context made available in portal tree

react-portal or react-modal are nice for popups, modals, and overlays that should be full-screen, generally centered in the middle of the screen.

react-tether is unknown to most React developers, yet it's one of the most useful tools you can find out there. Tether permits you to create portals, but will position automatically the portal, relative to a given target. This is perfect for tooltips, dropdowns, hotspots, helpboxes... If you have ever had any problem with position absolute/relative and z-index, or your dropdown going outside of your viewport, Tether will solve all that for you.

You can, for example, easily implement onboarding hotspots, that expands to a tooltip once clicked:

Onboarding hotspot

Real production code here. Can't be any simpler :)

<MenuHotspots.contacts>
  <ContactButton/>
</MenuHotspots.contacts>

Edit: just discovered react-gateway which permits to render portals into the node of your choice (not necessarily body)

Edit: it seems react-popper can be a decent alternative to react-tether. PopperJS is a library that only computes an appropriate position for an element, without touching the DOM directly, letting the user choose where and when he wants to put the DOM node, while Tether appends directly to the body.

Edit: there's also react-slot-fill which is interesting and can help solve similar problems by allowing to render an element to a reserved element slot that you put anywhere you want in your tree

Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
  • In you example snippet the confirmation popup won't close if you confirm the action (opposed to when you click on Cancel) – dKab Dec 29 '16 at 09:13
  • 1
    It would be helpful to include your Portal import in the code snippet. What library does `` come from? I'm guessing it's react-portal, but it'd be nice to know for sure. – stone Mar 15 '17 at 19:54
  • 1
    @skypecakes please consider my implementations as pseudo-code. I didn't test it against any concrete library. I just try to teach the concept here not a concrete implementation. I'm used to react-portal and code above should work fine with it, but it should work fine with almost any similar lib. – Sebastien Lorber Mar 15 '17 at 20:33
  • react-gateway is awesome! It support server side rendering :) – cyrilluce Jun 17 '17 at 10:21
  • I'm pretty beginner so will be very happy for some explanation on this approach. Even if you really render the modal in another place, in this approach you will have to check on every delete button if you should render the modal's specific instance. In the redux approach I have only one instance of the modal which is shown or not. Isn't it a performance concern? – Amit Neuhaus Jun 11 '20 at 20:01
9

A lot of good solutions and valuable commentaries by known experts from JS community on the topic could be found here. It could be an indicator that it's not that trivial problem as it may seem. I think this is why it could be the source of doubts and uncertainty on the issue.

Fundamental problem here is that in React you're only allowed to mount component to its parent, which is not always the desired behavior. But how to address this issue?

I propose the solution, addressed to fix this issue. More detailed problem definition, src and examples can be found here: https://github.com/fckt/react-layer-stack#rationale

Rationale

react/react-dom comes comes with 2 basic assumptions/ideas:

  • every UI is hierarchical naturally. This why we have the idea of components which wrap each other
  • react-dom mounts (physically) child component to its parent DOM node by default

The problem is that sometimes the second property isn't what you want in your case. Sometimes you want to mount your component into different physical DOM node and hold logical connection between parent and child at the same time.

Canonical example is Tooltip-like component: at some point of development process you could find that you need to add some description for your UI element: it'll render in fixed layer and should know its coordinates (which are that UI element coord or mouse coords) and at the same time it needs information whether it needs to be shown right now or not, its content and some context from parent components. This example shows that sometimes logical hierarchy isn't match with the physical DOM hierarchy.

Take a look at https://github.com/fckt/react-layer-stack/blob/master/README.md#real-world-usage-example to see the concrete example which is answer to your question:

import { Layer, LayerContext } from 'react-layer-stack'
// ... for each `object` in array of `objects`
  const modalId = 'DeleteObjectConfirmation' + objects[rowIndex].id
  return (
    <Cell {...props}>
        // the layer definition. The content will show up in the LayerStackMountPoint when `show(modalId)` be fired in LayerContext
        <Layer use={[objects[rowIndex], rowIndex]} id={modalId}> {({
            hideMe, // alias for `hide(modalId)`
            index } // useful to know to set zIndex, for example
            , e) => // access to the arguments (click event data in this example)
          <Modal onClick={ hideMe } zIndex={(index + 1) * 1000}>
            <ConfirmationDialog
              title={ 'Delete' }
              message={ "You're about to delete to " + '"' + objects[rowIndex].name + '"' }
              confirmButton={ <Button type="primary">DELETE</Button> }
              onConfirm={ this.handleDeleteObject.bind(this, objects[rowIndex].name, hideMe) } // hide after confirmation
              close={ hideMe } />
          </Modal> }
        </Layer>

        // this is the toggle for Layer with `id === modalId` can be defined everywhere in the components tree
        <LayerContext id={ modalId }> {({showMe}) => // showMe is alias for `show(modalId)`
          <div style={styles.iconOverlay} onClick={ (e) => showMe(e) }> // additional arguments can be passed (like event)
            <Icon type="trash" />
          </div> }
        </LayerContext>
    </Cell>)
// ...
fckt
  • 571
  • 4
  • 12
5

In my opinion the bare minimum implementation has two requirements. A state that keeps track of whether the modal is open or not, and a portal to render the modal outside of the standard react tree.

The ModalContainer component below implements those requirements along with corresponding render functions for the modal and the trigger, which is responsible for executing the callback to open the modal.

import React from 'react';
import PropTypes from 'prop-types';
import Portal from 'react-portal';

class ModalContainer extends React.Component {
  state = {
    isOpen: false,
  };

  openModal = () => {
    this.setState(() => ({ isOpen: true }));
  }

  closeModal = () => {
    this.setState(() => ({ isOpen: false }));
  }

  renderModal() {
    return (
      this.props.renderModal({
        isOpen: this.state.isOpen,
        closeModal: this.closeModal,
      })
    );
  }

  renderTrigger() {
     return (
       this.props.renderTrigger({
         openModal: this.openModal
       })
     )
  }

  render() {
    return (
      <React.Fragment>
        <Portal>
          {this.renderModal()}
        </Portal>
        {this.renderTrigger()}
      </React.Fragment>
    );
  }
}

ModalContainer.propTypes = {
  renderModal: PropTypes.func.isRequired,
  renderTrigger: PropTypes.func.isRequired,
};

export default ModalContainer;

And here's a simple use case...

import React from 'react';
import Modal from 'react-modal';
import Fade from 'components/Animations/Fade';
import ModalContainer from 'components/ModalContainer';

const SimpleModal = ({ isOpen, closeModal }) => (
  <Fade visible={isOpen}> // example use case with animation components
    <Modal>
      <Button onClick={closeModal}>
        close modal
      </Button>
    </Modal>
  </Fade>
);

const SimpleModalButton = ({ openModal }) => (
  <button onClick={openModal}>
    open modal
  </button>
);

const SimpleButtonWithModal = () => (
   <ModalContainer
     renderModal={props => <SimpleModal {...props} />}
     renderTrigger={props => <SimpleModalButton {...props} />}
   />
);

export default SimpleButtonWithModal;

I use render functions, because I want to isolate state management and boilerplate logic from the implementation of the rendered modal and trigger component. This allows the rendered components to be whatever you want them to be. In your case, I suppose the modal component could be a connected component that receives a callback function that dispatches an asynchronous action.

If you need to send dynamic props to the modal component from the trigger component, which hopefully doesn't happen too often, I recommend wrapping the ModalContainer with a container component that manages the dynamic props in its own state and enhance the original render methods like so.

import React from 'react'
import partialRight from 'lodash/partialRight';
import ModalContainer from 'components/ModalContainer';

class ErrorModalContainer extends React.Component {
  state = { message: '' }

  onError = (message, callback) => {
    this.setState(
      () => ({ message }),
      () => callback && callback()
    );
  }

  renderModal = (props) => (
    this.props.renderModal({
       ...props,
       message: this.state.message,
    })
  )

  renderTrigger = (props) => (
    this.props.renderTrigger({
      openModal: partialRight(this.onError, props.openModal)
    })
  )

  render() {
    return (
      <ModalContainer
        renderModal={this.renderModal}
        renderTrigger={this.renderTrigger}
      />
    )
  }
}

ErrorModalContainer.propTypes = (
  ModalContainer.propTypes
);

export default ErrorModalContainer;
kskkido
  • 59
  • 1
  • 2
0

Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch from props, do not pass mapDispatchToProps function to connect.

class ModalContainer extends React.Component {
  handleDelete = () => {
    const { dispatch, onClose } = this.props;
    dispatch({type: 'DELETE_POST'});

    someAsyncOperation().then(() => {
      dispatch({type: 'DELETE_POST_SUCCESS'});
      onClose();
    })
  }

  render() {
    const { onClose } = this.props;
    return <Modal onClose={onClose} onSubmit={this.handleDelete} />
  }
}

export default connect(/* no map dispatch to props here! */)(ModalContainer);

The App where the modal is rendered and its visibility state is set:

class App extends React.Component {
  state = {
    isModalOpen: false
  }

  handleModalClose = () => this.setState({ isModalOpen: false });

  ...

  render(){
    return (
      ...
      <ModalContainer onClose={this.handleModalClose} />  
      ...
    )
  }

}
Chance Smith
  • 1,211
  • 1
  • 15
  • 32
gazdagergo
  • 6,187
  • 1
  • 31
  • 45