paint-brush
ReactJS Custom Modal Component using Hooks and Portalsby@codebucks
14,363 reads
14,363 reads

ReactJS Custom Modal Component using Hooks and Portals

by CodeBucksJune 10th, 2021
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

Create reusable modal component in react js using hooks and portals. Using this modal you can render content dynamically with cool animation.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - ReactJS Custom Modal Component using Hooks and Portals
CodeBucks HackerNoon profile picture

Modal is a common UX element. A modal is a dialog box/popup window that is displayed on top of the current page. You must have used pop-ups and notifications for your website. For some people pop-ups are really annoying😫 if it doesn't behave as it should. It must have good UI/UX.

In this article, we're going to create an efficient Modal component🤩 from scratch without using any library.

Demo Link🖤: https://react-reusable-components.vercel.app/

Our main goal is to create an efficient modal which,

  • Has a good layout
  • Doesn't break ui when we use overflow in the parent component
  • Can render content Dynamically
  • Clean and Elegant animation
  • Looks good (good UI)
  • Have more control for User (like clicking outside can close modal) etc.

Let’s get started!

If you prefer video format then you can watch this video 📽👇

Create your react-app using,

npx create-react-app react-modal

For this tutorial, I'm going to use Sass so make sure you have installed node-sass package. To install it do,

npm install node-sass

Let's create a Basic Modal component

open App.js file.

clean🧹 unnecessary code.

Now create one button in the App.js file to open and close modal just like this 👇

<div className="App">
      <button>
        Modal
      </button>
</div>

Create one state to open and close modal.

Write below 👇 code:

import { useState } from "react";
import "./App.scss";

function App() {
  
  const [modal, setModal] = useState(false);
  const Toggle = () => setModal(!modal);
  
  return (
    <div className="App">
      <button className="clickme" onClick={() => Toggle()}>
        Modal
      </button>
    </div>
  );
}

export default App;

Line 6: Contains modal state which is false initially.

Line 7: A Toggle method to toggle modal state from false to true and vice-versa.

Line 11: Make sure to connect

Toggle()
method to onClick of the button.

Next, create Modal.js file and Write below 👇 code:

const Modal = () => {
  return (
    <div>
      Modal
    </div>
  );
};

export default Modal;

Now import it in the Modal in App.js file.

Line 17: Here we have imported `Modal` component. And passed modal state as shown in the props.

Now open Modal.js and write below code 👇

import Close from "./times-solid.svg";

const Modal = ({ show }) => {
  return (
    <>
     {
     show ?
     
     <div
        className="modalContainer" 
      >
        <div className="modal" >
          <header className="modal_header">
            <h2 className="modal_header-title"> Modal Title </h2>
            <button className="close" >
              <img src={Close} alt="close" />
            </button>
          </header>
          <main className="modal_content">
          This is Modal Content
          </main>
          <footer className="modal_footer">
            <button className="modal-close" >
              Cancel
            </button>

            <button className="submit">Submit</button>
          </footer>
        </div>
      </div>
      : null
     }
    </>
  );
};

export default Modal;

Line 3: Deconstruct Show from the props.

Line 7: We will display the modal only when the show state is true.

Line 9 to 30: This is the whole Modal layout. Modal Container div contains the modal.

  • In the modal div, There is one header that contains the modal title and close Button (You can use any icon for the close button).
  • The main tag contains the content of the modal.
  • Footer has 2 buttons one is submitted and another is canceled.

Now when you press a button modal will show and on pressing again it will close the modal.

First Let's add some styling to our modal.

Create a Modal.scss file and import it in the Modal.js file.

Copy and paste this styling in the Modal.scss file.

This will give your modal a better look.

Line 21: By applying this

backdrop-filter
you can make it look like frost-glass.

Let's add Close event in modal

In the App.js file pass toggle method as props in the modal just like this 👇

<Modal show={modal} title="My Modal" close={Toggle}/>

open Modal.js file and deconstruct close from the props.

import Close from "./times-solid.svg";

const Modal = ({ show, close }) => {
  return (
    <>
     {
     show ?
     
      <div
        className="modalContainer"
        onClick={() => close()}
      >
        <div className="modal" onClick={(e) => e.stopPropagation()}>
          <header className="modal_header">
            <h2 className="modal_header-title">Modal Title</h2>
            <button className="close" onClick={() => close()}>
              <img src={Close} alt="close" />
            </button>
          </header>
          <main className="modal_content">This is modal content</main>
          <footer className="modal_footer">
            <button className="modal-close" onClick={() => close()}>
              Cancel
            </button>

            <button className="submit">Submit</button>
          </footer>
        </div>
      </div>
      : null
     }
    </>
  );
};

export default Modal;

Line 3: Deconstruct Close from the props.

We have added close method in 3 places:

Line 16: At the close button.

Line 22: At the cancel button.

Line 11: We have also added a close method here too. Why? because whenever the user clicks outside it should close the modal. So here, when the user clicks on the modalContainer it closes the modal.

Line 13: here we have to stop these click events in the modal else it will close it so for that we have used e.stopPropagation().

hint: You can also add event Listener and add functionality in which when user clicks esc key, It closes the modal. (It is good for user experience)

Let's use Portals to render the Modal component

⏩ What🧐 are portals?

  • Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

⏩ Why🤔 should we use portals?

  • Sometimes when we use
    overflow
    or
    z-index
    properties in the parent component then we need child component (like modal or dialogues) to break container visually, and portals can be very handy to do that because it renders children outside of DOM hierarchy.

⏩ The syntax✍ for to create a portal👇

ReactDOM.createPortal
( 
element, 
DOM node where you want to render this element 
)

So let's implement portals in our Modal component.

To use the portal we have to create one more element in the dom.

Generally, our whole App renders in the div with the id root.

Open index.html file.

and above the root div create one more div with the id modal.

Just like this 👇

<div id="modal" />
<div id="root" />

Open Modal.js file and edit it just like this,

import ReactDOM from "react-dom";
import "./modal.scss";
import Close from "./times-solid.svg";

const Modal = ({ show, close }) => {
  return ReactDOM.createPortal(
    <>
     {
     show ?
     
      <div
        className="modalContainer"
        onClick={() => close()}
      >
        <div className="modal" onClick={(e) => e.stopPropagation()}>
          <header className="modal_header">
            <h2 className="modal_header-title">Modal Title</h2>
            <button className="close" onClick={() => close()}>
              <img src={Close} alt="close" />
            </button>
          </header>
          <main className="modal_content">This is modal content</main>
          <footer className="modal_footer">
            <button className="modal-close" onClick={() => close()}>
              Cancel
            </button>

            <button className="submit">Submit</button>
          </footer>
        </div>
      </div>
      : null
     },
    document.getElementById("modal")
    </>
  );
};

export default Modal;

Line 1: Import ReactDom.

Line 6: After return creates a portal using ReactDom.createPortal, As it's the first argument we have passed the whole modal component and for the second argument we have passed the dom node where we want to render it.

Line 34: We want to render our component in the div with id modal.

Let's make Modal content Dynamic:

open App.js file and pass title as a prop and content inside the component as shown below,

<Modal show={modal} title="My Modal" close={Toggle}>
        This is Modal content
</Modal>

Here we have passed the title as props and modal content as the children.

Open Modal.js and write,

(Final Modal.js code)

Line 5: Deconstruct

title
and
children
from the props.

Line 17: Insert title in the curly braces.

Line 22: Render children using the curly braces.

Now if you want to add a little animation in the modal you can watch the video or you can go to the git repository and read📚 code.

Thanks For Reading😄

Feel free to visit my youtube channel: @CodeBucks