How to create an efficient Modal component in React using Hooks and Portals
Tags: react, javascript, webdev, tutorial
Published: 2021-06-09 09:33:29

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 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 📽👇

{% youtube 5aG8peJsBVg %}

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 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:

{% gist https://gist.github.com/codebucks27/560b42066ef58e8989253a60d6750714/ea1e9d0325eac393cef4b0e437260fa74c9bf718 %}

**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 Modal in the `App.js` file.

{% gist https://gist.github.com/codebucks27/560b42066ef58e8989253a60d6750714 %}

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

Now open `Modal.js` and write below code 👇

{% gist https://gist.github.com/codebucks27/2c0c35db6079a9a0e1a7d8fd45500262/dcae42fd192235fb32fc5b23f69db2768276339c %}

**Line 3:** Deconstruct Show from the props.

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

**Line 9 to 30:** This is the whole **Modal layout**.
* ModalContainer div contains the modal
* In the modal div, There is one header which contains *modal title* and *close* Button (You can use any icon for close button).
* Main tag contains *content* of the modal.
* Footer has 2 buttons one is *submit* and another is *cancel*.

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 `Modal.scss` file and import it in the `Modal.js` file.

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

{% gist https://gist.github.com/codebucks27/b1222e8ed597bd839543af402749deef %}

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 a 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.

{% gist https://gist.github.com/codebucks27/2c0c35db6079a9a0e1a7d8fd45500262/caecd937e5f162327ab9407c475a7b38aff7accd %}

**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 close method here too. Why? because whenever user clicks outside it should close the modal. So here, when user clicks on the modalContainer it closes the modal.

**Line 13**: here we have to stop this 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 Modal component

> What🧐 is [portals](https://reactjs.org/docs/portals.html) ?

* 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. 

> Syntax✍ for to create portal👇

ReactDOM.createPortal
( 
element, 
DOM node where you want to render this element 
)
 
So let's implement portals in our Modal component.

To use 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,

{% gist https://gist.github.com/codebucks27/2c0c35db6079a9a0e1a7d8fd45500262/8731ac5e4f66023a1a2954d7e829cc1d6e690f00 %}

**Line 1**: Import ReactDom.

**Line 6**: After return create portal using `ReactDom.createPortal`, As it's first argument we have passed 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 props 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 title as props and modal content as the children.

Open `Modal.js` and write,

(Final Modal.js code)

{% gist https://gist.github.com/codebucks27/2c0c35db6079a9a0e1a7d8fd45500262 %}

**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.

If you have any question just ask in the comments😉

### Thanks For Reading😄

Feel free to visit my youtube channel: 
####[@CodeBucks](https://www.youtube.com/channel/UCeYt6blRBKuNrEg_-282fSA)