Search code examples
reactjsmaterial-ui

Migration to material-ui v4, I get warning for Modal component


Since upgrade material-ui to v4, I got some warnings with Modal component.

E.g

Failed prop type: Invalid prop children supplied to ForwardRef(Modal).

Function components cannot be given refs.

This is Modal code (warning 1):

import React from 'react';
import Proptypes from 'prop-types';
...

class DetailDialog extends React.Component {
  render() {
    const { classes, open, onClose } = this.props;

    return (
      <Dialog
        open={open}
      >
        ...
      </Dialog>
    );
  }
}

DetailDialog.propTypes = {
  open: Proptypes.bool,
  onClose: Proptypes.func,
};

export default DetailDialog;

This is Modal code (warning 2):

import React from 'react';
import PropTypes from 'prop-types';
...

class SelectCatDialog extends React.Component {
  render() {
    const { open, list, onClose } = this.props;

    return (
      <Dialog
        open={open}
        onClose={onClose}
      >
        ...
      </Dialog>
    )
  }
}

SelectCatDialog.propTypes = {
  open: PropTypes.bool,
  onClose: PropTypes.func,
}

SelectCatDialog.defaultProps = {
  list: [],
}

export default SelectCatDialog;

This is call Modal page code:

import React from 'react';
import DetailDialog from './components/DetailDialog';
import SelectProcDialog from './components/SelectProcDialog';

class Index extends React.Component {
  render() {
    return (
      ...
        <DetailDialog
          open={this.state.detailDialog}
          entity={this.state.currentDetail}
          onClose={this.handleDetailClose.bind(this)}
        />

        <SelectProcDialog
          open={this.state.catalogDialog}
          list={this.props.catalog}
          onOk={(value) => this.handleSelectCatalogOk(value)}
          onClose={() => this.setState({ catalogDialog: false })}
        />
      ...
    )
  }
}

export default Index;

What happened? Working fine in v3 version. Can someone answer?


Solution

  • Since V4, Dialog and Modal children must be able to hold a ref.
    The following can hold a ref:

    • Any Material-UI component
    • class components i.e. React.Component or React.PureComponent
    • DOM (or host) components e.g. div or button
    • React.forwardRef components
    • React.lazy components
    • React.memo components

    The error declares that you provide function component as a child to modal.
    To fix the error, change the function component to something that can hold a ref (e.g class component).