Alternative to window.prompt in React
Using Context, Hooks, and TypeScript
In this post, I will go over my implementation of an alternative to window.alert
, window.confirm
andwindow.prompt
using React.
All of the examples are written with TypeScript.
A demo with full source code is available at the end.
window.alert - shows a message
window.confirm - shows a message + returns true / false
window.prompt - shows a message + returns a string user input
The Result
Starting from the end, let’s see what we’re trying to achieve:
The above component is a Button with some behavior for onClick
, with the caveat that we want to warn the user before actually running the callback named doAction
.
This is somewhat similar to where we would use window.alert
or window.confirm
.
Let’s take a look at another example:
In the second example, our Button component adds a new string item to a list in its state. The string is defined by user input.
This is somewhat similar to where we would use window.prompt
.
usePrompt
Let’s have a look at how we implemented usePrompt
, a shared custom hook, which we used before in the result examples:
We can see that it’s just a simple hook that returns a triggerPrompt
callback. The “magic” still lays inside PromptContext
, which encapsulates a setPrompt
function that receives isOpen
and PromptProps
.
PromptContext
This may seem long, but it’s primarily types and default props when looking closer.
The interesting part is at the bottom, where we create PromptContextProvider
to wrap our app content. This makes PromptContext
capable of holding a global prompt state for isOpen
and props
, which we can access from anywhere using the usePrompt
hook from before.
The next thing to do is to wrap our app with PromptContextProvider
like so:
Lastly, we implement a custom Prompt
component to our liking, using any kind of Modal
component we prefer:
And that’s it!
Demo
Let’s see everything in action:
Demo in full screen:
https://lxvlw7.csb.app/
Full source code:
https://github.com/Liadshiran/react-prompt-context
Summary
I hope this tutorial was helpful for you with the use cases I covered.
And if not, it may hopefully have inspired you with ideas on how to leverage Context to make our lives as React developers easier and our code more generic and understandable.
Feel free to reach out on Twitter or LinkedIn:
@liad_shiran
linkedin.com/in/liad-shiran/
Liad