Create React Modal Popup with Material UI

By Digamber Rawat Last updated on
In this tutorial, we are going to build a simple and animated modal popup in React using Material UI.

React Modal Popup Tutorial

Modals are widely used component in React-based web and mobile applications.A Modal popup provides a simple solution to user interface related problems. A Modal window covers the entire screen and useful in displaying relevant information to the users. Modals are also known as Overlays, Dialogs etc. It constitutes a convention that covers the browser window with appropriate information keeping in front of the users.

How Does Modal Help Us?

  • When user user input is required.
  • To grab user’s attention.
  • Show extra information in context.

In this step by step React tutorial, you will learn to build various kind of popup modals in React. We will be taking the help of Material UI for developing Modals.

Prerequisites

To build modal popup in React, you must be aware of HTML & CSS and a basic understanding of React Js. You must have Node Js and create-react-app installed in your system.

Set up React 16+ Project

Run the command to initial React app setup.

npx create-react-app react-modal-material-ui

Get inside the project folder.

cd react-modal-material-ui

Install & Set Up Material UI

Material UI is a UI library that offers React components for super-fast, flexible and more comfortable web app development.

Run command in the terminal to install Material UI in React app.

# with npm
npm install @material-ui/core

# with yarn
yarn add @material-ui/core

Next, go to src/index.css file and import the Material UI official font-family and icons.

@import "https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap";
@import "https://fonts.googleapis.com/icon?family=Material+Icons";


body {
  margin: 0;
  font-family: "Roboto", sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  font-weight: 400;
}

Next, start the React app.

npm start

Create React Modal Component

In this step, we will start building a simple React model with Material UI. Before getting started to create a new folder inside the src directory and name it components.

After that create a two files inside components folder and name them simple-modal.component.js and animated-modal.component.js, then add the following code inside of it.

import React from "react";

export default function SimpleModal() {
    return (
        <div>
            <h3>React Simple Modal Example</h3>
        </div>
    );
}
import React from "react";

export default function AnimatedModal() {
    return (
        <div>
            <h3>React Simple Modal Example</h3>
        </div>
    );
}

Next, import the modal components in src/App.js file.

import React from 'react';
import './App.css';
import SimpleModal from "./components/simple-modal.component";
import AnimatedModal from "./components/animated-modal.component";

function App() {
  return (
    <div className="App">
      <SimpleModal /> <br />
      <AnimatedModal />
    </div>
  );
}

export default App;

Build Simple Modal in React

Next, we will create a simple modal using material UI. Import the Button component from Material UI in simple-modal.component.js file. This button will allow us to click on it and will open the popup.

import Button from '@material-ui/core/Button';

Place the button code inside the return() method in React.

<Button variant="contained" color="primary">
   Open Modal
</Button>

Next, add the following code in the modal file.

import React from "react";
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Modal from '@material-ui/core/Modal';

function rand() {
    return Math.round(Math.random() * 20) - 10;
}

function getModalStyle() {
    const top = 50 + rand();
    const left = 50 + rand();
    return {
        top: `${top}%`,
        left: `${left}%`,
        transform: `translate(-${top}%, -${left}%)`,
    };
}

const useStyles = makeStyles(theme => ({
    modal: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    paper: {
        position: 'absolute',
        width: 450,
        backgroundColor: theme.palette.background.paper,
        boxShadow: theme.shadows[5],
        padding: theme.spacing(2, 4, 3),
    },
}));

export default function SimpleModal() {
    const classes = useStyles();
    const [modalStyle] = React.useState(getModalStyle);
    const [open, setOpen] = React.useState(false);

    const handleOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };

    return (
        <div>
            <Button variant="contained" color="primary" onClick={handleOpen}>
                Open Modal
            </Button>

            <Modal
                aria-labelledby="simple-modal-title"
                aria-describedby="simple-modal-description"
                open={open}
                onClose={handleClose}
            >
                <div style={modalStyle} className={classes.paper}>
                    <h2>Simple React Modal</h2>
                    <p>
                        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi accumsan odio enim, non pharetra est ultrices et.
                    </p>
                </div>
            </Modal>
        </div>
    );
}

Create Animated Modal Popup in React

Next, we will build an animated modal using material UI. Include the following code in animated-modal.component.js file.

import React from 'react';
import Button from '@material-ui/core/Button';
import { makeStyles } from '@material-ui/core/styles';
import Modal from '@material-ui/core/Modal';
import Backdrop from '@material-ui/core/Backdrop';
import Fade from '@material-ui/core/Fade';

const useStyles = makeStyles(theme => ({
    modal: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
    },
    paper: {
        backgroundColor: theme.palette.background.paper,
        border: '2px solid #000',
        boxShadow: theme.shadows[5],
        padding: theme.spacing(2, 4, 3),
    },
}));

export default function AnimatedModal() {
    const classes = useStyles();
    const [open, setOpen] = React.useState(false);

    const handleOpen = () => {
        setOpen(true);
    };

    const handleClose = () => {
        setOpen(false);
    };

    return (
        <div>

            <Button variant="contained" color="secondary" onClick={handleOpen}>
                Open Animated Modal
            </Button>

            <Modal
                aria-labelledby="transition-modal-title"
                aria-describedby="transition-modal-description"
                className={classes.modal}
                open={open}
                onClose={handleClose}
                closeAfterTransition
                BackdropComponent={Backdrop}
                BackdropProps={{
                    timeout: 500,
                }}
            >
                <Fade in={open}>
                    <div className={classes.paper}>
                        <h2>Animated React Modal</h2>
                        <p>
                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi accumsan odio enim.
                        </p>
                    </div>
                </Fade>
            </Modal>
        </div>
    );
}

Conclusion

In this React tutorial, we learned how to create simple and animated modal popups in React using Material UI library. We have gone through various steps such as setting up the React app, building the file structure and implementing the modal. You can check out the complete code on GitHub by clicking on the below button.

GitHub Repo

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.