Skip to main content
ReactJS Modal with Material UI

ReactJS Modal with Material UI

in this tutorial, I will let you know how to create a modal box popup using material UI. I’ll use material ui and react 17 to create a customize modal component.

React is a JavaScript library for building advanced user interfaces. It is usually used with CSS to style web pages. Material UI is a React component library that provides cool Material Design elements. In this tutorial, we will use Material UI to style a modal popup.

The material ui provides a modal component for creating dialogs, popovers, lightboxes, or whatever else.

How To Work Material UI with Reactjs

React is a JavaScript library for building user interfaces, while Material UI is a React specific UI framework. The two work well together, as Material UI components accept React props. If you are new to React, we recommend that you read the official React documentation before continuing.

React uses a declarative paradigm that makes it easier to reason about your application and achieve development goals, such as building an interactive user interface.

What’s Modal Box

Modal is basically a dialog box or popup window that is used to provide information or display confirmation messages to the user.

It can be used to render content that can be further used for making a decision. It gets displayed on top of the current page. Modal consists header, body, and a footer.

We will use React state to control whether the modal is visible or not. Initially, the modal will not be visible. We will add a button to our React component and use onClick event to show the modal.

React Modal component Using Material UI

First, we will set up our React app using create-react-app. Then, we will install Material UI in our React app.

Next, we will create one React component called Modal using Material UI. Finally, we will use this Modal component in our App.js file.

Create & install Dependencies

Run the command to initial React app setup. This command will create a basic React app with a user interface.

npx create-react-app react-modal-material-ui
cd react-modal-material-ui
npm install @material-ui/core

After the command finishes, you will have a folder called react-modal-material-ui in your current directory. This folder contains a file called index.js which is the starting point for our React app.

Start the React app

npm start

Basic Modal Component

We can create a basic model by using below react script.

The following code will create a new model. First, we will create a new file called Model.js and add the following code. The model will have two properties, close and open modal box.

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' as '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() {
  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>
  );
}

Custom React Modal Box Component

We are going to build a simple and animated modal popup in React using Material UI.

The following code will create a new custom model. First, we will create a new file called CustomModal.js and add the following code. The model will have properties, open, close handler and data.

Let’s create our custom modal component using react, we’ll extend material-ui’s Modal component and add our extra features and contents.

import * as React from 'react';
import {Box, Card, Button, Divider, CardHeader, CardContent, CardActions} from '@mui/material';
import Typography from '@mui/material/Typography';
import Modal from '@mui/material/Modal';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';

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

export default function CustomModal(props) {
  let data = props.data
  const [open, setOpen] = React.useState(false);
  const handleOpen = () => setOpen(true);
  const handleClose = () => setOpen(false);
 
  return (
    <div>
      <Button onClick={handleOpen} size="small">{props.title}</Button>
      <Modal
        open={open}
        onClose={handleClose}
      >
        <Card sx={{ maxWidth: "80%", left:"15%", top: '10%',position:"fixed" }}>
        <CardHeader
        style={{backgroundColor: "#0288d1", color: "white"}}
        action={
          <IconButton aria-label="settings" onClick={handleClose}>
            <CloseIcon className="colorW" />
          </IconButton>
        }
        title={data.DetailType}
        subheader={data.startTime}
      />
      <Divider/>
      <CardContent sx={{maxHeight:400, overflow: "overlay"}}>
          <Typography sx={{ mt: 2 }} style={{paddingLeft: 20, paddingRight: 20, overflowWrap: "break-word"}}>
          <Grid direction='row' container spacing={1}>
              {data.Description}
            </Grid>
          </Typography>
          </CardContent>
          <Divider/>
          <CardActions style={{float:"right"}}>
          <Button autoFocus onClick={handleClose} color="primary">Close</Button>
          </CardActions>
        </Card>
      </Modal>
    </div>
  );
}

In order to call the customModal component, we will have to add the code provided below into the App.js file. Doing this will allow us to use the customModal component in the application.

import Modal from '../CustomModal'

const AlertDetails = () => {
let data = {};
data.description = "hello! i am js admin";

return (<Modal title="openModal" data={data} />)
}

Leave a Reply

Your email address will not be published. Required fields are marked *