Show React dialogs fluently with hooks and promises

Suppose you have a React component that displays a modal dialog and returns the result:

The typical way to use it would be to have a state variable controlling if it should be displayed or not, and a function for handling the return value. Something like this:

Nothing special, but I don’t like how the logic is located in different functions instead of a continuous flow. And what if we wanted to have multiple dialogs? We would typically repeat everything for each dialog…

What if we could open the dialog in a more fluent way, similar to JavaScript confirm:

Let’s implement a hook that wraps the dialog component in a promise!

Now we can open the dialog and handle the return value in a single flow, even with nested dialogs:

Pretty neat! :-)

This entry was posted in Development, Tutorials and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *