Build This Cool PopUp / Modal with React and CSS
A nicely styled version of an alert()
, the modal, the popup. One of the sometimes annoying yet necessary elements of the web.
For this blog, I created a modal using React and CSS, and I’m going to show you how I went about it.
I assume there are millions of ways to achieve this. I’d love your feedback if you have any improvements.
the code on GitHub
Tutorial
Table of Contents
- Preliminary Junk
- CheckOut Component
- PopUp Component
- The Styles
- Conclusion
Preliminary Junk
To begin, I set up a create-react-app
deleted the default junk and set up a file structure like this:
To make this demo sweet, I set up a fake shopping cart.
The only thing that functions on this screen is the “Checkout!” button. I’m going to skip the code for this, but you can find it in the here.
CheckOut Component
I set up a CheckOut
component that has a table
displaying the items the user is purchasing and some other stuff for the sake of demoing the popup.
What’s important for the popup functionality are these lines of code:
On line 9, I set up a useState
hook for toggling the popup on and off.
On line 11, I set up a variable called duringPopUp
that will conditionally add the style " during-popup"
to the elements it is applied to. This class will darken the background-color
of those elements. I apply like this:
On line 48, I have a line of code that conditionally renders a PopUp
component. That component receives setPopUp
as props. This way I can toggle the PopUp
off from within the PopUp
component.
PopUp Component
My PopUp
component is set up like this:
The content of PopUp
can be whatever you need. I set all the buttons to simply toggle the component off. In reality, if someone wanted more bones, the MORE BONES! button would give them MORE BONES!
The Styles
Again, I’m going to skip most the styles in CheckOut.css
file. Most of them set up the fake cart and make the buttons look a little nicer. Here’s what’s important for the popup.
Darken Background Colors in Checkout.js
Remember, this style is added when the popUp
state is true
. It darkens the background-colors
wherever it is applied.
Styles for elements in PopUp.js
These are the styles for the outer most div in the PopUp
container:
The important piece is position: fixed;
. This will cause the component to render exactly where it is positioned by top
and left
. Since it is fixed
, it will stay in the same position even if you scroll.
Conclusion
Hope this helps you create the most irritating advertisement the web has ever seen. Kidding, of course, but I do hope this helps with your popup design. I’d love some feedback. Hit me up at jason.melton2@gmail.com
. Thanks for reading. Best, Jason.