For enquiries call:

Phone

+1-469-442-0620

Easter Sale-mobile

HomeBlogProgrammingHow to Create a React Native Portal with Examples

How to Create a React Native Portal with Examples

Published
05th Sep, 2023
Views
view count loader
Read it in
14 Mins
In this article
    How to Create a React Native Portal with Examples

    In React, when we render a child element on any main components, the child component overlaps on the main component, causing a disturbance in the application’s structure. We can use the React portal concept to get rid of such disturbances. React portals allow us to place a child component directly inside another show and have it adhere to that element with overflow restrictions. The ReactDOM can be used as createPortal (the child and the container) that will help us address overflow-related component rendering issues. To know more about usereducer hook in React, click here. 

    In this tutorial, we’ll walk you through the basics of React portal to help you get started with your React Native full course jumpstart in React. Also, we’ll explain the use of React portal with the help of noteworthy examples.  

    Let’s Start!

    What is React Portal? 

    React Portal is a first-class technique to render children into a Document Object Model (DOM) node existing outside the parent component's DOM hierarchy. Any renderable React child, such as an element, string, or fragment, is the first argument (Child), whereas the second argument is the DOM element.

    Syntax of React Portal 

    The simple syntax is seen below, where the child and container are supplied. The ReactDOM has been given two properties; child and container. The renderable child component is the first component created by the createPortal function. The following syntax can be used to generate a React DOM create portal:

    ReactDOM.createPortal(child, container)

    React-Native Portals 

    You can use the React context API to create a primary portal that allows you to transport a React Native portal component from one location to another, regardless of hierarchy. We will create a PortalProvider that will manage a table of gates, with the key being the gate name and the value is the element to be shown. Each element within the Portal would have accessibility to a teleportation mechanism that could transport a component to any specified portal by name.

    Top Considerations When Using Portals 

    There are a few things to keep in mind when using React portals. You won't be able to see the effectiveness of portals unless you keep these considerations in mind:

    1. Event Bubbling works as intended. Regardless of where the Portal node is in the DOM, event bubbling will propagate actions to the React tree predecessors.
    2. React influences portal nodes and their lifecycle. When using portals to render child elements, React retains control over the lifespan.
    3. Portals have a significant effect on the DOM structure. Portals do not affect the React elements tree and only impact the html.com structure.
    4. When using portals, always define an html.com component as it is the portal component's mount point.

    The Importance of Using Portals 

    A portal behaves the same way as any other component of React. You can find and access portals anywhere in the DOM tree. It has robustness, potential, and capabilities more than its counterpart React components. During the development stage of a large web project, consider rendering an element somewhere within the app that is not the original component's location.  

    Here are a few benefits of using React portals:

    • React portals use context to streamline data transfer seamlessly.
    • Event Bubbling allows communication between the parent component and the child component.

    Event Bubbling Through React Portals 

    Although a portal can be anywhere else in the DOM tree, it functions as a typical React child in any other way. Elements like contextual work the same irrespective of whether the kid is a portal, as the Portal remains in the React tree regardless of the position in the DOM tree.

    React portal facilitates event bubbling. An event launched from inside a portal will spread to ancestors in the enclosed React tree, even if those items are not ancestors in the DOM tree. Considering the below HTML structure:

    render() {
        return (
          <div className="App" onClick={this.handlePageClick}>
            <header className="App-header">
              <img src={logo} className="App-logo" alt="logo" />
              <p>AK at BeautifulCode is good at React!</p>
              <p>
                {" "}
                To ask him questions please{" "}
                <button onClick={this.toggleModal}>Cick here!</button>
              </p>
              <p>Total number of Page Clicks so far {this.state.pageClicks} </p>
            </header>
            {this.state.showModal && (
              <Modal>
                <p>This would send an Email to AK. Are you sure?</p>
                <div className="buttons">
                  <button onClick={this.toggleModal}>Yes</button>
                  <button onClick={this.toggleModal}>No</button>
                </div>
              </Modal>
            )}
          </div>
        );
      }

    When and How Do We Use Portals? 

    Generally, we use portals for positioning and styling elements in a sophisticated way. Many times, a modal may be nested as a child component. Modifying the child without detaching from the parent may be strenuous. Under such scenarios, we can leverage portals to pull off the targeted React portal modal out of the hierarchy without disturbing the parents.

    The following are some of the most typical React portal use-cases:

    • Tooltips
    • Floating menus
    • Widgets
    • Modals

    Now that we have understood the importance of using portals let’s explore further and check how to use them.  

    To explore more, get yourself registered for the mobile development course and start your learning journey.

    React Portals Examples

    We have prepared a list of React portal examples below, divided into three sections: the HTML, the JavaScript, and the CSS. Let's break down each section to construct the portal concept in React JS. Suppose we want to run the examples below. We can build an HTML file and combine the HTML, CSS, and JavaScript with the appropriate dependencies. Then, we will run the instances or use several online React compilers to make these examples work in action.

    1. Example Using Html Content 

    The HTML portion follows. We've used two div tags in this section, one for the main component and the other for showing pop-ups with messages.

    <!--Div to show main component -->
    <div id="example">
    </div>
    <!--Div to popup showing -->
    <div id="popup"></div>

    2. Example Using JavaScript Content 

    Below is the React JavaScript code. We have developed two React portal functional components, one for showing the major component and the other for showing the notifications. There will be a button on the main component; click it, the status of the display will shift from false to true, and a pop-up will appear. When we connect to dismiss the open pop-ups, the situation will change back to false, and the pop-ups will disappear. For simplicity, the show status for these pop-ups has been set to false.

    First Components, used for the pop-ups
    
    //Here, we are creating a feature that will display in the form of the popups, and we can also include some text messages on this model
    Class Pop extends React.Component {
        constructor(props) {
        super(props)
        //Capture details of the div element
        this.element = document.createElement('div')
        }
        //This function is called automatically after rendering of the components
        componentDidMount() {
        //Append the element to the popup model
        document.getElementById('popup').appendChild(this.element)
        }
        //This function unmount the displayed popups, and this is also et automatically called
        componentWillUnmount() {
        //Remove the element popups from the appended previously
        document.getElementById('popup').removeChild(this.element)
        }
        render() {
        //Create a portal for handling our cases
        return ReactDOM.createPortal(
        //Take Child and element
        this.props.children,
        this. element
        )
        }
        }

    This unit comprises the child element of pop-ups, the significant components, and the second or default components:

    class Portalexample extends React.Component {
        constructor(props) {
        super(props)
        //Initialise the model as false which means the popups will be closed at the starting time and later according to the operations the value will be either true or false.
        this.state = {showhideModel: false}
        this.manageShowHide = this.manageShowHide.bind(this)
        this.manageHide = this.manageHide.bind(this)
        }
        //Change the true and false of the show hide will be managed in this function and it will be called when clicked the button .
        manageShowHide() {
        this.setState({showhideModel: true})
        }
        manageHide() {
        this.setState({showhideModel: false})
        }
        render() {
        //Click the button to handle Show and hide
        constshowpopups = this.state.showhideModel ? (
        <Pop>
        <div>
        Hello friends <button onClick={this.manageHide}>Close</button>
        </div>
        </Pop>
        ) : ''
        return (
        <div>
        The portal example <button onClick={this.manageShowHide}>Display Model</button>
        {showpopups}
        </div>
        )
        }
        }
        //Attach the component with the div of html which we have created
        ReactDOM.render(<Portalexample />, document.getElementById('example'))

    3. Example Using CSS Component 

    The CSS code for developing the pop-up when you click the main component's button is provided below:

    #popup
    {
        position: fixed;
        z-index: 997;
        }
        /* popup designing with CSS is goes here */
        #popup div {
        background-color: green;
        /*  Define the height of the popups */
        height: 99%;
        /*  Define the position of the popups */
        position: fixed;
        top: 0;
        /*  Define the display of the popups */
        display: flex;
        align-items: center;
        left: 0;
        /*  Define the width of the popups *
        width: 99%;
        justify-content: center;
    }

    Explanation of Images

    The first image of the screen is for the major components, while the second image of the display is for the pop-up. When you click the display model button, the second image appears, and when you click the close button on the second image, the first image on the screen appears.

    React Portals: How Does It Work? 

    Before delving deeper into the portal's operation, it is essential to understand when is the appropriate time to employ the notion of the Portal. An overflow occurs when displaying a component since the child elements may not be contained within the component's actual node. We may immediately place the child component within another feature using the portal, and it will manage the overflow condition.  

    At the time of creating a portal, we pass two qualities. The first is the child, and the second is the container. Out of the two, the first attribute is any renderable component's child. (renderable means it can be rendered and can be visible to the end-users).

    Explaining Portal with an Example

    In this section, we’ll create a simple React app with basic functionality that will display a modal when we click on the button. The whole app will be in the root DOM hierarchy, whereas the modal will be placed outside the DOM.

    First, in the index.html, a div contains an ‘app-root.’ This is our main DOM tree. However, we need to create another upper-order hierarchy to display our modal outside the tree. Let’s create another div and call it ‘modal-root’:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8" />
      <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
      <meta name="theme-color" content="#000000" />
      <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
      <title>Playing around with Reactjs 16 portals</title>
    </head>
    <body>
      <noscript>You need to enable JavaScript to run this app.</noscript>
      <div id="app-root"></div>
    <div id="modal-root"></div>
      <!--
        This is the div that you need to add!
        -->
    </body>
    </html>

    In the App.js file, we will create buttons to activate the ON/OFF function. Let’s dedicate one button to turn ON the modal and another button inside the modal to turn it OFF. Let’s create:

    import React, { Component } from 'react';
    import './App.css';
    export class App extends React.Component {
      state = {
        isOpen: false,
      }
      toggle = () => {
        this.setState(({ isOpen }) => ({ isOpen: !isOpen }))
      }
    render() {
        const modal = this.state.isOpen ? (
          <Modal>
            <div className="modal-background"> //imported from the bulma library
                This modal is into a portal ! <button onClick={this.toggle}>Hide Modal</button>
            </div>
          </Modal>
        ) : ''
        return (
          <div >
            Click on it ! => < button onClick={this.toggle} >Show modal</button >
            {modal}
          </div >
        )
      }
    }

    You will see the displayed React portal modal between the <Modal> tag. We need to create a component that will create the portal to our modal-root div. Let’s create:

    import React, { Component } from 'react';
    import ReactDOM from 'react-dom'; //Import the ReactDOM here to use the portal
    import './App.css';
    class Modal extends Component {
      render() {
        return ReactDOM.createPortal( //creation of the portal to render it in the modal-root div
          this.props.children,
          document.getElementById('modal-root')
        )
      }
    }
    export class App extends React.Component {
      state = {
        isOpen: false,
      }
      toggle = () => {
        this.setState(({ isOpen }) => ({ isOpen: !isOpen }))
      }
    render() {
        const modal = this.state.isOpen ? (
          <Modal>
            <div className="modal-background">
                This modal is into a portal ! <button onClick={this.toggle}>Hide Modal</button>
            </div>
          </Modal>
        ) : ''
        return (
          <div >
            Click on it ! => < button onClick={this.toggle} >Show modal</button >
            {modal}
          </div >
        )
      }
    }

    Here the React createPortal() function takes two arguments, where the first is the child, and the container will be the second. Our guide has modal and modal-root as the first and second arguments, respectively.  

    The last step is to render the parent, the <App /> in our case. We need to render the parent into the root div as highlighted below:

    import React, { Component } from 'react';
    import ReactDOM from 'react-dom'; //Import the ReactDOM here to use the portal
    import './App.css';
    class Modal extends Component {
      render() {
        return ReactDOM.createPortal( //creation of the portal to render it in the modal-root div
          this.props.children,
          document.getElementById('modal-root')
        )
      }
    }
    export class App extends React.Component {
      state = {
        isOpen: false,
      }
      toggle = () => {
        this.setState(({ isOpen }) => ({ isOpen: !isOpen }))
      }
    render() {
        const modal = this.state.isOpen ? (
          <Modal>
            <div className="modal-background">
                This modal is into a portal ! <button onClick={this.toggle}>Hide Modal</button>
            </div>
          </Modal>
        ) : ''
        return (
          <div >
            Click on it ! => < button onClick={this.toggle} >Show modal</button >
            {modal}
          </div >
        )
      }
    }
    ReactDOM.render(<App />, document.getElementById('root'));
    export default App;

    Like the createPortal() function, the render() function takes two arguments: the first is the entire application, and the container is the second. Our guide represents the <App> tag and main-root as the first and second arguments, respectively. 

    You will observe that the modal is nested out from our main DOM hierarchy. Thanks to React portals, we can now style our modal without disturbing the parent(s). Once you understand the React portals, consider using React testing library portals to level up. Check out our blog posts about React virtual DOM – React JS essentials for the next steps.

    Conclusion

    React Portal is applicable whenever we need to render child elements outside the standard DOM hierarchy without disrupting event propagation through the React element tree hierarchy. It is essential for rendering modals, tooltips, pop-up messages, and many other components. Use the concepts discussed in this tutorial to build projects yourself and explore more.  

    Trying React portal hooks and other basic implementations is an excellent way to advance difficulty and hone your skills. Furthermore, you can enroll in the KnowledgeHut’s React Native full course and get trained by IT industry experts.

    Frequently Asked Questions (FAQs)

    1How does event bubbling work for children inside a React portal?

    Regardless of its position in the DOM tree, the portal maintains its location in the React tree. It implies that effectively fired in a portal will propagate upstream to ancestors in the contained React tree, even if the DOM tree is located elsewhere.

    2How does the portal work?

    React portals offer a first-class means to render and enable child elements to live inside a Document Object Model (DOM) node, typically found outside the DOM. This React portal element appears outside the parent component's DOM hierarchy.

    3What is Portal in React Native?

    In React native, a portal allows users to render components at different locations in the parent tree. It's similar to modal and is seldom used to render material that should appear above other elements. It requires the host component to be rendered at a specified point in the parent tree.

    4How do you make a component portal?

    Leverage createPortal function to make a component portal. The following syntax can be used to establish a React DOM create portal:

    ReactDOM.createPortal(child, container)
    5Is both the arguments mandatory in ReactDOM.createPortal?

    No! The first argument in the ReactDOM.createPortal function is mandatory, whereas the second one is optional. Children can be rendered into a DOM node that stays beyond the hierarchy of the DOM element using portals.

    6When using Portal, what is the second argument?

    The first argument (Child) is any renderable React child, such as a component, string, or fragment, is the first argument (Child). A DOM element (container) is the second argument.

    Profile

    MD SOHAIL

    Author

    Sohail is an SRE, professionally experienced in IaaS, cloud computing, automation, and deployment. He is a python enthusiast and best-seller at Fiverr known for his result-driven deliverables and satisfactory customer service. He loves to experiment, write, and work out. When he is not actively involved in all these, he reads and explores new things.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon