Member-only story
How To Create An Async Modal With React
4 min readDec 16, 2023
Have you ever wondered how to open a pop-up asynchronously from the code and wait for the user’s actions? Today we are going to create such a component!
Requirements
Let’s think about what we want to accomplish. Our modal has to:
- Be opened from anywhere in the code.
- Return a promise, that resolves with
true
when the user confirms andfalse
when the user rejects. - Be configurable.
Components
To bring our desires into life a couple of components needs to be implemented:
- Modal. The modal should allow rendering of an arbitrary header, content, and confirmation/rejection texts.
- Context. The context will be responsible for displaying the modal on the screen.
- Hook. The hook will encapsulate interaction with the context and return a function to open the modal. The function itself will return a promise that resolves when the user confirms or rejects the modal.
The Modal
Let’s start by creating a new folder under src
called modal
. Inside the modal let’s create two files: Modal.js
and Modal.css
. Keep in mind that if you are not using the latest version of React, then it should be…