An in-depth guide on React Portals
What are the features of React Portals?
In React.js, there is just one root element, and all other components operate as child elements. What if I want to utilize a modal in the component? We need to construct a component for it, which will function as a child element in the project. How can I implement that feature if I don’t wish to build another child element for the modal? It is feasible using React Portal.
What is a React portal?
In general, a portal is something that serves as a gateway to anything else. In this case, the React portal serves as a gateway for adding an element that does not exist in the React DOM hierarchy. It allows an element to be rendered outside of its component hierarchy, i.e., in a separate component. This is an important feature that was introduced in React v16 and is still emphasized in React V18 features and updates.
Why do we use React Portal?
Portals are typically utilized when we wish to put or design an element that is not attached to a parent. Sometimes the modal is in a child component that is deeply nested. Fixing a child’s style without compromising the parent’s style can be quite tough. That is why we employ React portal.
What are the features of React Portals?
- It uses React 16 version and its official API for creating portals.
- It transports its children component into a new React portal which is appended by default to document. body.
- We can target any user-specified DOM element.
- supports server-side rendering.
- Supports returning arrays here we don’t have to wrap the div element.
- It doesn’t produce any DOM mess.
- No dependencies, minimalistic.
When to use it?
The common use cases of React portal include:
- Modals
- Tooltips
- Floating menus
- Widgets
What is the syntax of React Portal?
ReactDOM.createPortal(child, container)
Here,
ReactDOM: ReactDOM is a package that provides specific DOM methods that can be used at the highest level of the web application to enable an effective way to manage DOM web page features.
createPortal: create a Child outside the root element
child: we can add any child which can be renderable such as an element, fragment, or string.
container: Dom element. We have to give the id name where we want to render the element. Ex. getElementById (“portal-example”)
How to use React Portal?
Here, we are going to create a simple project, which displays modal on button click. Using modal, we’ll check how to display modal outside the DOM hierarchy.
Project Structure:
Steps to create a React Portal.
- Add a div element and give id to it. Using the id, we are going to add the element to it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <title>React Portal Exampl</title> </head> <body> <div id="root"></div> <div id="portal-example"></div> <!-- In the portal-example div, we are going to add our modal. --> </body> </html>
You can see that we have created a new div element in the DOM. You can see figure 2 for a better understanding.
-
Create Portal globally.
Here we have created a global component named “PortalComponent”. Now whatever children we want to put in another DOM element we have to just put them inside the PortalComponent. The logical functionality of hiding and showing we have implemented in the App component.
PortalComponent.js
import { Component } from 'react' import ReactDOM from 'react-dom' class PortalComponent extends Component { render() { return ReactDOM.createPortal ( this.props.children, document.getElementById("portal-example") ) } } export default PortalComponent;
For creating a portal, we have to import ReactDOM. ReactDOM provides a portal object. The arguments of createPortal we have discussed earlier. In the first argument, we have passed here “this.props.children”. By using “this.props.children”, we can use children then it takes all the elements whatever we have passed from top-level. Here you can see the output of “this.props.children”, it contains the div and button element we have passed in the wrapper of PortalComponent.
2. Use it in the App component.
App.js
import React, { Component } from "react"; import PortalComponent from "./PortalComponent"; import { Button } from "@mui/material"; class App extends Component { constructor() { super(); this.state = { isOpen: false, title: "Show Modal" } // This binding is necessary to make `this` work in the callback this.handleModal = this.handleModal.bind(this) this.hideModal = this.hideModal.bind(this) } handleModal() { this.setState({ isOpen: !this.state.isOpen, title: this.state.title === "Hide Modal" ? "Show Modal" : "Hide Modal" }) } hideModal() { this.setState({ isOpen: false, title: "Hide Modal" }) } render() { return ( <> <div> <h1>App Component in root element</h1> <Button sx={{ height: 36, backgroundColor: 'green' }} onClick={this.handleModal} title="mui-button" variant="contained"> {this.state.title} </Button> </div> { this.state.isOpen ? <PortalComponent> <h1>Hello, This is modal from portal-example.</h1> <Button sx={{ height: 36, backgroundColor: 'green' }} onClick={this.hideModal} title="mui-button" variant="contained"> Hide Modal </Button> </PortalComponent> : null } </> ) } } export default App;
In the App component, we have imported our PortalComponent, for making the wrapper to nested elements. we are going to display the modal with a button click. When we display the modal, you can see that the modal is displayed outside the root DOM element and inside the “portal-example” element. Here, we have two figures. In figure 4 you can see that when the modal is hidden that time no new element is created. But when we open the modal at that time it shows that in the “portal-example” element we have nested elements like button and <h1> tag.
When the modal is hidden, the “portal-example” div has no element, as shown above.
Now when we have displayed the modal you can see that in the “portal-example” there is a modal and <h1> tag created. We can say that we have created a modal that is not present in the root element.
Conclusion
React Portals are useful for developers since they demonstrate how to construct a distinct react DOM element. This blog has taught us about react gateways and where we may utilize them. Finally, we built a project for the portal usage and learned the concepts practically.
What is an Excel Add-in?
MS Excel Add-in is a kind of program or a utility that lets you perform fundamental processes more quickly. It does this by integrating new features into the excel application that boosts its basic capabilities on various platforms like Windows, Mac & Web.
The Excel Add-in, as part of the Office platform, allows you to modify and speed up your business processes. Office Add-ins are well-known for their centralized deployment, cross-platform compatibility, and AppSource distribution. It enables developers to leverage web technologies including HTML, CSS, and JavaScript.
More importantly, it provides the framework and the JavaScript library Office.js for constructing Excel Add-ins. In this tutorial, we will walk through the basic yet effective process of creating the Excel Addin using ReactJS.
Prerequisites for setting up your development environment
Before you start creating Excel Add-ins, make sure you have these prerequisites installed on your PC.
- NPM
- Node.js
- Visual Studio
- A Microsoft 365 account with a subscription
Office Add-ins benefit businesses with faster operations and processes. In Office Add-ins, you can use familiar technologies like HTML, CSS & JavaScript to create Outlook, Excel, Word, and PowerPoint Add-ins. In this blog, we learned how to create an Excel Addin with React library from scratch and how to create tables, filter & sort data in Excel using Excel Add-in.
Author Bio: Ajay Patel – Technical Director, iFour Technolab Pvt. Ltd.
A Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. With a sharp understanding and technical acumen, he has delivered hundreds of Web, Cloud, Desktop, and Mobile solutions and is heading the technical department at iFour Technolab, an esteemed Microsoft 365 development company. Looking to hire dedicated React developers? Contact us now.
For more articles visit: acuteblog.com