Use a modal when we need to present important information or prompt the user for an action without navigating away from the current screen, such as confirmations, alerts, or form submissions.
How to use Material UI modal
Key takeaways:
Modals are UI elements used to interrupt a user's workflow to present important information, such as alerts or confirmation dialogs, often requiring immediate action.
Modals are commonly used for alerts (e.g., unsaved work), confirmations (e.g., deleting an item), and actions that require user attention.
The
Modalcomponent in Material UI simplifies the process of integrating modals in React applications, providing essential features like handling visibility (openprop) and custom backdrops (slots.backdrop).Material UI modals offer customization through props such as
closeAfterTransition,disableAutoFocus,hideBackdrop, andonClose, allowing you to tailor the modal’s behavior to your needs.Adding transitions, like fade-ins, enhances the user experience. The
Fadecomponent can be used to create smooth animations when showing or hiding the modal.
Material UI is an open-source React UI library used to integrate reusable and pre-built components in the React application. It implements Google’s Material Design to build visually appealing React components.
In this Answer, we'll explore the implementation of the Material UI modal in our React application. Before that, let's get an idea of what modals are and why we need them.
What is a modal in Material UI?
Modals are user interface elements that interrupt the normal workflow of the users to divert their attention toward a piece of information that requires immediate confirmation. This information is presented in the form of a pop-up or dialog box. Material UI provides a simple and elegant way to implement modals in your React applications using the Modal component.
Examples
We often use modals while using mobile and web applications. Some of the examples are:
Alerts and messages: They display important messages and alerts. For example, when we are leaving an application without saving our work, an alert modal is displayed.
Confirmation or actions: They display confirmation messages and actions. For example, when we update an item in a list, we are prompted to confirm whether we want to make the update. This confirmation prompt is an example of a modal.
Note: Before getting started, please install Material UI in your React application.
Modal props types
Here’s a breakdown of the common props for the Modal component:
Prop name | Description | Example |
| The content to be displayed inside the modal. |
|
| A boolean that determines whether the modal is shown or hidden. |
|
| This prop defines the component for the backdrop in the modal. It's part of the new API replacing |
|
| This allows you to pass props to the backdrop element inside the modal. |
|
| If |
|
| If |
|
| If |
|
| A callback function that is fired when the modal requests to be closed. You can use this to handle the close action. |
|
Creating a simple modal with Material UI in React
In this section, we will see how to create a simple modal using Material UI. Let’s consider an everyday use case where we have to delete an item. Once we click the “Delete” button, we are shown a pop-up that confirms if we want to delete the item or not. In the code example below, we’ll see how to implement this use case. Please click the “Run” button to execute the code:
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: 450,
bgcolor: "rgb(139, 140, 247)",
boxShadow: 5,
p: 5,
borderRadius:5
};
export default function App() {
const [open, setOpen] = React.useState(false);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
return (
<div>
<Button variant="contained" color="error" onClick={handleOpen} sx={{marginLeft:'43vw'}}>Delete</Button>
<Modal open={open} onClose={handleClose}>
<Box sx={style}>
<Typography sx={{marginBottom:2 , color:"white"}}>
Confirm deletion?
</Typography>
<Button variant="contained" onClick={handleClose} color="error" sx={{marginRight:5 , border:"1px solid white"}}>Yes</Button>
<Button variant="text" onClick={handleClose} sx={{color:'white'}}>Cancel</Button>
</Box>
</Modal>
</div>
);
}
The code explanation is given below:
Line 5: We import
Modalcomponent from the@mui/material/Modalmodule.Line 21: We create a
useStatevariable,open, to keep a record of the state of theModalcomponent.Lines 22–23: We define the
handleOpenandhandleClosefunctions that open and close theModalrespectively, by setting the value ofopen.Line 27: We create
Buttonthat executes thehandlOpenfunction on theonClickevent and eventually opens theModal.Line 28: We create the
Modalcomponent that consists of theopenandonCloseprops.The
openprop takes theopenstate variable. If theopenprop has atruevalue, then theModalis displayed; otherwise, it disappears.The
onClosefunction executes thehandleClosefunction when the user clicks outside the modal and sets theopenstate variable tofalse.
Note: The first descendent of the Modal component should be the Box component; otherwise, an error will arise.
Adding transitions
We can add a fade in transition by wrapping the Box component with the Fade component. To view the transaction in action, please click the “Run” button below:
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";
import Fade from '@mui/material/Fade';
const style = {
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
width: 450,
bgcolor: "rgb(139, 140, 247)",
boxShadow: 5,
p: 5,
borderRadius:5
};
export default function App() {
const [open, setOpen] = React.useState(false);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
return (
<div>
<Button variant="contained" color="error" onClick={handleOpen} sx={{marginLeft:'43vw'}}>Delete</Button>
<Modal open={open} onClose={handleClose}>
<Fade in={open}>
<Box sx={style}>
<Typography sx={{marginBottom:2 , color:"white"}}>
Confirm deletion?
</Typography>
<Button variant="contained" onClick={handleClose} color="error" sx={{marginRight:5 , border:"1px solid white"}}>Yes</Button>
<Button variant="text" onClick={handleClose} sx={{color:'white'}}>Cancel</Button>
</Box>
</Fade>
</Modal>
</div>
);
}
We can see the code explanation below:
Line 6: We import the
Fadecomponent from the@mui/material/Fademodule.Line 30: We define the
Fadecomponent with theinprop that fades in the wrapped components when the value istrue, and fades out when the value isfalse.
Explore the following projects for hands-on practice in creating real-world applications with React. You can enhance these projects by incorporating Material-UI for a polished and visually appealing design.
Conclusion
Material UI modals are a versatile tool that can be used to create dialog boxes, pop-ups, forms, and much more. By using the Modal component, we can quickly add interactive elements to the React application that provide a smooth user experience. Customize modals with transitions, form elements, and advanced styling to match the app’s needs. Remember to always consider accessibility and user experience when implementing modals in your projects.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
When to use a modal?
What is the difference between Material UI and Semantic UI?
Why Material UI is better than Bootstrap?
Free Resources