React Confirm Dialog as a service

Use promise, singletons and functions to simplify the process

Alexys Gonzalez
quadminds
2 min readNov 28, 2018

--

Creating a confirmation window is a simple task that can be achieved with a simple code of javascript, but when applying it in React it becomes a more complicated task. Even more when you need that functionality in different parts of an application (for example: when confirming a delete action of a record).

To simplify the creation of a Confirmation dialog in React, we can create an autonomous component of the application and use it through different methods and promises.

You can see an example in the following link.

Next we will see how to put together a list of Tasks and how to create an action to erase them:

First we create the main component

Then, we will add items to the state

Add the render

And finally we add the function to delete items

All the previous steps will take us to the basic functionality to erase an item.

To continue, if we want to implement a confirmation dialog before proceeding with the erase action, we will build the autonomous component that returns a promise, that, when resolved, will give us the value of the user’s response (true or false).

First of all we will create the component

This basic component will show us a basic dialog with two options (OK, Cancel).

To do so, we will add a static function that places the component in a different container than the main render of the application (like a React Portal) and we will return the reference.

The create function, originates a div and adds it to the body of the document, then returns the reference of the React render with the rendered component to be able to interact with it later.

To make the dialog show, we must create a function that changes the state isOpen to true and, in addition, returns a promise that is resolved when the user accepts or cancels the action.

For this we must unset the function resolve from the promise so that it can be called upon in the handlers of the component:

Then we instantiate a component in a file:

And finally we use the instance in the handler to eliminate the item, resolving the promise with async / await:

At this point we will have a confirmation dialog that we can use in any function, as if it were a confirm.

We can also customize the message or the title by the configuration of the objects to the create and show functions. You can see detailed example in the following link.

Conclusion

With this technique we can simplify the implementation of simple tasks such as a confirmation dialog, avoiding the creation of additional status or repeated components in the renders.

--

--

Alexys Gonzalez
quadminds

Software Architect (ReactJS, NodeJS, Micro-services, MongoDB, PostgreSQL, Typescript). Architect in Phinxlab.