“disableBackdropClick of ForwardRef(Dialog) is deprecated” – Solution and Example
After recently updating my Material UI Core package (@material-ui/core) in a React project from 4.11.4 to 4.12.2 I began getting the following warning from my <Dialog/>
components:
Failed prop type: The prop `disableBackdropClick` of `ForwardRef(Dialog)` is deprecated. Use the onClose prop with the `reason` argument to filter the `backdropClick` events.
The prop disableBackdropClick
has been made redundant, and now requires the user to handle this logic using onClose
. The onClose
function is passed two arguments: event and reason.
<Dialog
onClose={(event, reason) => {
if (reason !== 'backdropClick') {
onClose(event, reason)
}
}}
/>
This is fine if you have a small project with simple functionality. Unfortunately the project I was working on had many Dialog components used across the code base. Each handling disableBackdropClick
in their own way.
Solution
My solution (to save time) was to create a wrapper for the Dialog. This allows the project to use the latest MUI package without an excessive amount of refactoring.
import React, {useState} from "react";
import Container from "@material-ui/core/Container";
import Dialog from "@material-ui/core/Dialog";
function DialogMigrate({
children,
disableBackdropClick,
disableEscapeKeyDown,
onClose,
...rest
}) {
const handleClose = (event, reason) => {
if (disableBackdropClick && reason === "backdropClick") {
return false;
}
if (disableEscapeKeyDown && reason === "escapeKeyDown") {
return false;
}
if (typeof onClose === "function") {
onClose();
}
};
return (
<Dialog onClose={handleClose} {...rest}>
{children}
</Dialog>
);
}
export default function App() {
const [open, setOpen] = useState(true)
return (
<Container>
<DialogMigrate
open={open}
disableEscapeKeyDown
onClose={() => {
// Whatever you want to run here on close.
setOpen(false)
}}
>
<p>Dialog content goes here...</p>
</DialogMigrate>
</Container>
);
}
The <DialogMigrate/>
component could be refactored to be more succinct. I have left it like this to show exactly what is happening.
[support-block]
To have a play with this and see it live, take a look at the Codesandbox here.
For more React hints and tips take a look at the React Category for this site!