How to create a popup modal in React


Posted 4 years ago by Ryan Dhungel

Category: React Hooks Web Development React CSS

Viewed 14596 times

Estimated read time: 7 minutes

In this tutorial, you will learn to create a session based popup modal in React. we will be using bootstrap4 for styling.

 

You can create a fresh new project using create-react-app to follow along this tutorial. First lets load bootstrap CDN links in public/index.html
We will need to load boostrap css along with bootstrap js, jQuery and popper js.


This is what you final index.html should look like

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"
      integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />

    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script
      src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
      integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"
      integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"
      integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

 

Now lets go ahead and create a modal component. You can create modal component inside src folder src/Modal.js

 

How this react popup modal will work

 

  • First we are going to create a state using useState hook
  • Then add two methods showModal and closeModal to show hide modal
  • It will be session based so each time a new tab is opened
  • The popup will apper after 2 seconds
  • The next time modal will appear only if user closes the tab and opens new one
  • This way we dont annoy user by showing modal each time
  • This is how your final Modal.js should look like

 

src/Modal.js

import React, { useState, useEffect } from 'react';

const Modal = () => {
  const [isShown, setIsShown] = useState(false);

  const showModal = () => {
    setIsShown(true);
  };

  const closeModal = () => {
    setIsShown(false);
  };

  const dynammicModalClass = () => (isShown ? { display: 'block' } : '');

  useEffect(() => {
    if (!sessionStorage.popupModal) {
      const timer = setTimeout(() => {
        setIsShown(true);
        sessionStorage.popupModal = 1;
      }, 2000);

      return () => clearTimeout(timer);
    }
  }, []);

  // return isShown ? <h3>Modal content</h3> : null;
  return isShown ? (
    <div className="modal" style={dynammicModalClass()} id="channelModal">
      <div className="modal-dialog modal-dialog-centered" role="document">
        <div className="modal-content">
          <div className="modal-header">
            <h5 className="modal-title text-light">Free Measure. Free Quote.</h5>

            <button
              onClick={closeModal}
              style={{ color: '#fff' }}
              type="button"
              className="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>

          <div className="modal-body">
            <div className="row">
              <div className="col-6">
                <img src="image.jpg" alt="react-hooks" />
              </div>

              <div className="col-6">
                <p className="lead text-light">
                  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae cumque, assumenda cupiditate
                  incidunt reiciendis earum
                </p>
              </div>
            </div>
          </div>

          <div className="modal-footer">
            <button className="btn-lg btn btn-primary">
              <span style={{ color: '#fff' }}>
                <i className="fa fa-phone mr-1 " />
                <a href="tel:01234567" style={{ color: '#fff' }}>
                  0123 4567{' '}
                </a>
              </span>
            </button>
            <button onClick={closeModal} type="button" className="btn btn-lg">
              No Thanks
            </button>
          </div>
        </div>
      </div>
    </div>
  ) : null;
};

export default Modal;

 

Now that we have our modal, you can import modal to App.js and use

App.js

import React from 'react';
import Modal from './Modal';

function App() {
     return (
          <div>
               <h2 className="text-center">
                    <Modal />
                    <p>your content goes here... write 2000 words long article</p>
               </h2>
          </div>
     );
}

export default App;

 

Styling react popup modal

 

Finally lets add some styling to have box shadow effect on popup modal so that it looks better. You can put the following css in src/index.css

* p {
    font-size: 16px;
}

.modal-content {
    -webkit-box-shadow: -1px 1px 5px 9px #333;
    -moz-box-shadow: -1px 1px 5px 9px #333;
    box-shadow: -1px 1px 50px 1px #333;
}

.modal-header,
.modal-body,
.modal-footer {
    background: #002849 !important;
}

.modal-body img {
    width: auto;
    height: 150px;
}

 

Conclusion

 

Congratulations. you have build a react popup modal using bootstrap. This is a very simple bootstrap modal that you can customize further the way you like.
If you have any issues or suggestions, leave your comments below. Thanks.

 

Interested in building FullStack React Node MongoDB powered Ecommerce app from Scratch to Live Server?