By WalkingTree August 12, 2020
Modals are an essential part of building an application. It is a simple and clean way of showing data to the end-user with fewer efforts. Thousands of websites are already using modal extensively. Now how can you implement a modal in your React application? Well, there are many ways to do so. Numerous UI libraries are available which provide an attractive modal interface.
One of the easiest ways is to create a reusable component by creating a wrapper for these interfaces and use them wherever needed. But, although this method seems easy to implement, it has many problems. Let’s take a look at what the problem is and how React Hooks can help overcome it.
Let’s say you have to add another modal to your application. What will you do? Any developer would simply add another state to open or close the modal, handler to toggle the state on a click, and lastly, add the component (<ModalBase/>). For any modal that you integrate, the same amount of code has to be used, or let’s just call it Code Redundancy. This can get out of control real soon.
Let’s see how we can fix this issue using React Hooks. Usually, there are 2 types of code in an application –
- Dynamic: Content of the modal and other props
- Static: the process of toggling the modal’s open state
The solution is really simple. You have to isolate both the parts into 2 different codes using hooks. Now, this can be done in 2 parts –
- Part 1: Moving the code related to the modal content and its related functionality to its custom hook exposed in the form of a container. Additionally another custom hook to use the modal container to get the context and handle the process of toggling and closing the modal. Finally, a modal component which will make use of both the hooks to handle the complete modal functionality, container for the dynamic part and hook for the static.
- Part 2: Using Context API to make the modal accessible throughout the application.
Read on to know more about modals and how it can be used with React Hooks.
We had a requirement to be able to indicate and provide feedback on a video in the form…
The rapid growth in technology is driving enterprises to modernize new apps, service delivery channels, and digital platforms….