Guest User

Untitled

a guest
Apr 25th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. import React from 'react'
  2. import PropTypes from 'prop-types'
  3. import { Formik } from 'formik'
  4. import Dialog, {
  5. DialogActions,
  6. DialogContent,
  7. DialogContentText,
  8. DialogTitle
  9. } from 'material-ui/Dialog'
  10. import Button from 'material-ui/Button'
  11.  
  12. class FormDialog extends React.Component {
  13. static propTypes = {
  14. opener: PropTypes.func.isRequired
  15. }
  16.  
  17. state = {
  18. open: false
  19. }
  20.  
  21. /**
  22. * The dialog can serve many purposes by opening with a completely new state
  23. * this should be validated eventually, but for now newState should have:
  24. *
  25. * title: string
  26. * contentText: string
  27. * validationSchema: yup schema object
  28. * initialValues: formik initialValues
  29. * render: formik render prop
  30. * onSubmit: formik/dialog submit handler
  31. */
  32. handleOpen = newState => {
  33. this.setState(() => ({
  34. ...newState,
  35. open: true
  36. }))
  37. }
  38.  
  39. handleClose = () => {
  40. this.setState({
  41. open: false
  42. })
  43. }
  44.  
  45. /**
  46. * Calls the onSubmit passed via handleOpen with the
  47. * formik submit args and the dialog close function
  48. * (values, options: { setSubmitting, setErrors }, handleClose)
  49. */
  50. handleSubmit = (...formikSubmitArgs) => {
  51. this.state.onSubmit(...formikSubmitArgs, this.handleClose)
  52. }
  53.  
  54. render () {
  55. const {
  56. open,
  57. title,
  58. contentText,
  59. validationSchema,
  60. initialValues,
  61. render
  62. } = this.state
  63.  
  64. return (
  65. <div>
  66. {this.props.opener(this.handleOpen)}
  67. <Dialog open={open} onBackdropClick={this.handleClose}>
  68. <DialogTitle>{title}</DialogTitle>
  69. <Formik
  70. validationSchema={validationSchema}
  71. initialValues={initialValues}
  72. onSubmit={this.handleSubmit}
  73. render={formikProps => {
  74. const { handleSubmit, isSubmitting } = formikProps
  75. return (
  76. <form onSubmit={handleSubmit}>
  77. <DialogContent>
  78. <DialogContentText>{contentText}</DialogContentText>
  79. {render(formikProps)}
  80. </DialogContent>
  81. <DialogActions>
  82. <Button onClick={this.handleClose}>Cancel</Button>
  83. <Button
  84. type='submit'
  85. color='secondary'
  86. disabled={isSubmitting}
  87. >
  88. Submit
  89. </Button>
  90. </DialogActions>
  91. </form>
  92. )
  93. }}
  94. />
  95. </Dialog>
  96. </div>
  97. )
  98. }
  99. }
  100.  
  101. export default FormDialog
Add Comment
Please, Sign In to add comment