9

I'm using material-ui's Dialog component for my React application. How do I set my component to a variable so that I can call the onShow() method?

tinazheng
  • 163
  • 1
  • 3
  • 11

2 Answers2

8

When adding the Dialog component, just add a ref to it (ref="dialog" for example):

<Dialog ref="dialog" title="..." actions="...">
  dialog content
</Dialog>

And then you can reference it from your owner component code by using this.refs.dialog.onShow(...).

The Dialog component page actually uses refs behind the scenes, as you can see from its source code.

lyosef
  • 6,092
  • 2
  • 27
  • 20
  • 6
    `onShow` is now deprecated: http://material-ui.com/#/components/dialog and opening should be handled through the `open` prop – TrySpace Nov 23 '15 at 13:50
  • 2
    In all the examples it shows a button with dialog on it to launch what if I want to launch in the way the OP is asking for AND hide the dialog button.. – landed May 25 '16 at 09:58
2

I recommend reading Dan Abramov's answer on how to implement a modal in React.

In order to use material-ui dialog you can replace the DeletePostModal in his example with the following:

import { deletePost, hideModal } from '../actions';
import React, {Component} from 'react';
import {connect} from "react-redux";
import {Button, Dialog, DialogActions, DialogTitle} from "material-ui";
import PropTypes from 'prop-types';

const DeletePostModal = ({ post, dispatch }) => (
  <Dialog open={true}>
       <DialogTitle>Delete post {post.name}?</DialogTitle>
            <DialogActions>
                 <button onClick={() => {
                      dispatch(deletePost(post.id)).then(() => {
                           dispatch(hideModal());
                      });
                  }}>
                        Yes
                  </button>
                  <button onClick={() => dispatch(hideModal())}>
                        Nope
                  </button>
        </DialogActions>
   </Dialog>
)

export default connect(
  (state, ownProps) => ({
    post: state.postsById[ownProps.postId]
  })
)(DeletePostModal)
chenop
  • 4,743
  • 4
  • 41
  • 65