
How to show pop-up Modals in your React web-app ?
17 November, 2022
8
8
1
Contributors
Modals are the modern way of displaying pop-up information in web-apps . It provides a cooler perspective to the website and makes information more related to the correct component .
React Portal : A Quick Introduction
To display a popup in your React app , you have to break the DOM hierarchy . Modals are displayed over a html node just like overlays . But updating the DOM directly is discouraged in React , since React has its own virtual DOM which internally updates the real DOM . Here comes React Portal as a savior .
React Portal allows you to break the DOM hierarchy and show up the modal in a respective html node . Portal internally spins up a "Portal" and handles all the DOM updates internally , without you accessing the Real DOM.
Steps to Follow :
1. Create your Modal component in React
Now this component will have the required modal design . Though there are many ways to implement background style and functionalities , I prefer a particular way of defining the modal and overlay in 2 different functions and then export it from the same component.
2. Create your background overlay
We pass a onClick handler to the Overlay function because we also need to close the modal when the user clicks outside the modal .
3. Change the index.html file
.png?type=webp)
This is a index.html file from one of my personal project
Your index.html file initially looks like this . Now you need to mention the tags where the modals will be rendered , i.e. , we need to define the hierarchy.
Add these two lines before <div id="root"></div> . These specifies the hierarchy and your modal will be displayed accordingly.
4. Use React.createPortal along with React Hooks
Now navigate to the component which triggers the display of the Portal . Remember to manage a state which in turn displays and hides the modal accordingly .
The react state handles the display of the Modal accordingly , so that we can logically display and hide the component.
The React.createPortal function takes two arguments , one of them is the modal component that you want to show and the other one is the target tag id where the modal will be rendered .
That's it ! You have successfully implemented the React Portal . Make your modals informative and minimalist .
This blog is open for reviews . Please feel free to share your views on this topic . Drop a like if this has been useful for you . Thanks !
reactjs
develevate
howto