0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】Warning: Failed prop type: The prop `open` is marked as required in `ForwardRef(Modal)`, but its value is `null`.の対処法

Last updated at Posted at 2021-12-23

症状

MaterialUIのModalを使用したとき、以下の警告が表示されました。 翻訳すると、「警告:失敗したプロップタイプ:プロップ「open」は「ForwardRef(Modal)」で必須としてマークされていますが、その値は「null」です。」でした。 「openが必須だが、openにnullが入っている」から警告されているようです。
warn
Warning: Failed prop type: The prop `open` is marked as required in `ForwardRef(Modal)`, but its value is `null`.

解決策

なぜか、useStateのopenの初期値をnullにしていたため、発生していました。 MaterialUIそのままだと、falseなのになぜそのまま使わなかった。。。

以下はMaterialUIのBasic modalから引用。

Modal.js
import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Typography from '@mui/material/Typography';
import Modal from '@mui/material/Modal';

const style = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: 400,
  bgcolor: 'background.paper',
  border: '2px solid #000',
  boxShadow: 24,
  p: 4,
};

export default function BasicModal() {
  //ここをなぜかnullで設定していた
  const [open, setOpen] = React.useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);

  return (
    <div>
      <Button onClick={handleOpen}>Open modal</Button>
      <Modal
        open={open}
        onClose={handleClose}
        aria-labelledby="modal-modal-title"
        aria-describedby="modal-modal-description"
      >
        <Box sx={style}>
          <Typography id="modal-modal-title" variant="h6" component="h2">
            Text in a modal
          </Typography>
          <Typography id="modal-modal-description" sx={{ mt: 2 }}>
            Duis mollis, est non commodo luctus, nisi erat porttitor ligula.
          </Typography>
        </Box>
      </Modal>
    </div>
  );
}

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?