Learn To Create React Modal Popup With material UI

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

 

Significance of Modals:

It is useful when:

  • we need the user input.
  • we have to grab the user’s attention.
  • we need to show extra information in the context.

 

How To Build Various Kind Of Popup Modals In React

Step 1- Prerequisites

For building Modal Popup in React, we must be first well aware of HTML and CSS along with some understanding of React JS. We must have node-js and create-react-app installed in our system.

 

Step 2- Set Up React 16+ Project

Here, we need to run the given command to initialize the React app setup.

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

 

Next, we get inside the project folder:

cd react-modal-material-ui

 

Step 3- Install And Setup Material UI

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

So, we run the 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

 

Further, we 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

 

Step 4- 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 two files inside the 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 is to 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;

 

Step 5- Build Simple Modal In React

In this fifth step, we will create a simple Modal using Material UI. Then, we 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>

 

Then, 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>
    );
}

 

Step 6- Create Animated Modal Popup In React

further, we have to 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>
    );
}

 

Summary

So, throughout this guide, we have learnt how to create simple and animated modal popups in React using Material UI library. We have seen various steps such as setting up the React app, building the file structure and implementing the modal. Hope that you have understood it completely.

 

Thanks

Leave a Reply

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