Create a modal in React.js without a component library

Utkarsh Goel
2 min readFeb 22, 2021

Modals are a great way to create user experiences where the user does not have to be taken to a new page in your application, especially if its for a very small element of your application.

Take for example:

https://deploif.ai

The above modal, however, is built using the Chakra UI component library. As the title promises, we are going to try to make a modal without the use of any component libraries.

Pre-requisites

I am going to assume that the React app has already been created using CRA. So I am just going to create a Modal component which can be ultimately plugged into a parent component.

Let’s get started

Firstly, let’s create a component file Modal.js.

I’ll give you the code first.

And then let’s break it down if you didn’t already stop reading.

The two divs

We need two divs, one parent div that covers the whole screen, because that’s what modals do, and a child div that has the actual content.

The styles of the parent div make for a transparent backdrop, with slight shadow from rgba(0,0,0,0.4)

To center the child div in the center, justifyContent and alignItems properties are essential to set to center.

Then you can go ahead and start making your modal content in the child div.

There is one rather complex-looking part of this code:

modalRef.current.contains(e.target)

This piece of code exists to make the modal closable when the user clicks outside the modal content, in the backdrop area. Since modalRef has been assigned to the child div , it makes it possible to detect whether click events happen within, or outside the div.

Now, for the last part: setVisible

This comes from a parent component as a prop. It is a part of the React useState hook and has been declared in a parent component as:

const [visible, setVisible] = useState(false);

You need to control how you render your Modal component. The visible state enables us to do that in the parent component.

Use the Modal component:

<Modal visible={visible} setVisible={setVisible} />

Finally, create a button and call setVisible(true) in the parent component. That will show the modal!

The result of the code above.

One question before you go…

Why are you not wanting to use a component library? There are so many that you can use out there!

Got further questions? Can that code get better?

Tweet at me: javachipd (https://twitter.com/javachipd)
My webpage: https://utkarshgoel.dev

--

--