Helen Efebe
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Pop-ups are among the best ways to grab a user’s attention on the web. That’s why they are often used as a primary marketing tool for generating and promoting leads. There are different ways to handle pop-ups in React, but React Portals are the best way to handle pop-ups and render models because they allow the child component to be rendered out of the parent hierarchy and perform event delegation. In this article, you will learn how portals are created and gain a better understanding of how they work. You’ll also learn the difference between ReactDOM.createportal and render methods. ## Prerequisites To understand what will be discussed in this article, it is recommended that you have a basic knowledge of the following: HTML, learn more about it [here](https://www.w3schools.com/html/default.asp) CSS, Learn more on it [here](https://www.w3schools.com/css/default.asp) JavaScript. Visit [here](https://www.w3schools.com/js/default.asp) to learn more ReactJS. Learn more [here](https://www.w3schools.com/react/default.asp) ## Introduction In React, we have the Component hierarchy. It refers to the tree of components in a page and how a React page is structured. The component hierarchy has a mother-child relationship between elements, meaning the child elements are displayed within their parent. When creating a modal in React using conventional methods instead of React Portals, the modal component is passed to its mother element, where it will be rendered. This practice results in an issue: the parent element's content still gets stacked on top of the modal. ReactPortal was introduced to solve this issue. ReactPortals makes it possible to render a child element outside of its parent hierarchy while maintaining the parent-child relationship. Let’s see how to create a modal in React, and then we will compare it to when a modal is created with the `createPortal` method from React Portal ## Create a Pop-up in React Create a new React project by running the command below in your terminal: ```javascript npx create-react-app reactPortal ``` After few minutes, a new React app will be created. Your app’s name is **reactPortal** Navigate into your project’s folder by running the command line below ```javascript cd reactPortal ``` Open the project on localhost:3000 using the command below ```javascript npm start ``` Open the project in your IDE to see your codebase Now that we have our app running on localhost: 3000 in our browser and our project open in our Integrated Development Environment(IDE) we can proceed by making some edits and removing the unwanted files. Then we will create new components for our project. Now we have what is in the image below. ![](https://hackmd.io/_uploads/ByX-06zFn.png) ## Create a Conventional React Pop-up In our App.js component, we will add these lines of code. This React function contains a simple demo, which we will work on in this article. Copy and paste this into your IDE, remember to add `import React from react` at the top of each component. ```javascript function App() { return ( <div className="App" style={BACKGROUND_STYLES} > <div className="Text" style={CONTENT_WRAPPER_STYLES} > <h1>Interesting facts about pop-ups</h1> <ul> <li>The user can not miss a pop-up</li> <li>Great marketing strategy</li> <li>It's best to build them using ReactPortal</li> </ul> </div> <button>Open Modal</button> <Modal> <h1>A Simple pop-up</h1> <p>Hey there, <br /> Now you can build ReactPortals</p> </Modal> </div> ); } ``` We have some text content, a `button`, and a `modal` in the code above. We want the button to open up the `modal` when it is clicked. For that, we will pass the `modal` into a separate component as a child element. ## The Modal Component Within our **Modal.Js** component, we will paste the code below. This is where our modal will be displayed, as it has been passed here. ```javascript function Modal({children}) { return ( <div> <div> {children} </div> </div> ) } ``` On line 1 in the code above, we have `{childre}` passed as an argument and rendered in line 5. This means that `modal` is a child of the component where it is currently located, and I want it to display here. Back in the App.js component, we will call Modal Component by pasting `import Modal from './Modal'` at the top. Now we have our modal showing in the browser ## Activate the Open Pop-up Button Here we need to change the state of the button from non-active to active, which can be done using useState. In our App.js, we will import useState from React and use it in our code by pasting the code below at the top of our file. ```javascript import React, { useState } from 'react'; ``` Still in App.js, paste the code below after the `function` declaration and the `return` keyword ```javascript const [isOpen, setIsOpen] = useState(false) ``` useState is set to an initial state of false and assigned to isOpen and setIsOpen. Paste this in the App.js file, right above the return. ```javascript <button onClick={( ) => setIsOpen(true)}>Open Modal</button> <Modal open={isOpen} onClose={() => setIsOpen(false)}> <h1>A Simple pop-up</h1> <p>Hey there, <br /> Now you can build ReactPortals</p> </Modal> ``` In the App.js file, update the button and modal with the code above. The button has an `onClick` function that changes the state of `setIsOpen` to true. In the modal, open is set to `isOpen`. Now the modal knows to open when it is clicked. The `onClose function` will close the modal when it is clicked. The next step is to connect this logic to our modal component. ```javascript function Modal({open, children, onClose}) { if (!open) return null return ( <div> <div style={OVERLAY_STYLES} /> <div style={MODAL_STYLES}> {children} <button onClick={onClose}>Close Modal</button> </div> </div> } ``` Let’s replace the content of the function in our modal file with the code above. On the modal function, we have called the open and onClose functions. These are the functions we defined in the parent component. On the second line, nothing is expected to happen if it's not open. If it is open, we need a way to close it. On line eight, we have a button where the `onClose` function is activated. ## Add Some Styles Now that we have created a React `modal` let's add some styles. To do this, add these styles at the top of each component. ```css const CONTENT_WRAPPER_STYLES = { position: 'relative', zIndex: 1 } const BACKGROUND_STYLES = { position: 'relative', zIndex: 2, backgroundColor: 'gray', padding: '20px', margin: '25px' } ``` App.js styles ```css const MODAL_STYLES = { position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', backgroundColor: '#FFF', padding: '50px', zIndex: 1000 } const OVERLAY_STYLES = { position: 'fixed', right: 0, top: 0, left: 0, bottom: 0, backgroundColor: 'rgba(0, 0, 0, 7)', zIndex: 1000 } ``` Modal.js styles ## Issues Encountered when Creating Portal in React the Conventional way Now our model is complete, but there is a stacking issue that makes the contents of the site to display on pop-ups. This stacking issue is a result of CSS zIndex attribute. The zIndex place containers on each other depending on their numbers, you can read more on this [here](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Understanding_z-index) The content of our page is stacked on the overlay of our portal. This proved to be a problem for developers that had no lasting solution. Luckily, React Portal was introduced; this was a tested and trusted solution to this problem. Developers could now build pop-ups and not worry about the stacking issue. Let us see how we can create our pop-ups using React Portal ## Create Pop-ups Using React Portal React Portal makes it possible to render our modal outside of the root element. It is common knowledge that React is a Single Page Application (SPA). Everything within our app is rendered in the root element. For our portal to display above everything else on our page, we will create another element within which the modal will be rendered. ```javascript <body> <div id="root"></div> <div id="portal"></div> </body> ``` In the `Index.html file`, we have the body of our app with two divs in it. The first div with an id of the `root` is where the entire app is running. The second div with the id of `portal` is where our modal will run. The next step is to connect our modal with this element. To do this, we will import ReactDom. ## Install React DOM React components are rendered into the HTML DOM (Document Object Model) using the JavaScript library ReactDOM. The creation of user interfaces (UIs) for React apps is its intended usage. ReactDOM acts as a link between the web page's actual HTML DOM elements and the hierarchy of React components; this is the property that has the method for creating our ReactPortal. ```javascript import ReactDOM from 'react-dom' ``` Let’s paste this code at the top of our Modal.js component. Wrap Modal Component in ReactDOM.createPortal() ReactDom has numerous properties, and we will be using the createPortal property to connect our modal component to the portal element. ```javascript return ReactDOM.createPortal( <div> <div style={OVERLAY_STYLES} /> <div style={MODAL_STYLES}> {children} <button onClick={onClose}>Close Modal</button> </div> </div>, document.getElementById('portal') ) ``` On the first line, we are returning `ReactDom.createPortal()` within which is the component it will be creating, which in this case is our modal component `document.getElementById('portal')` connects the `modal` to an HTML element where we want it displayed, which in this case is the div tag with an id of portal. This is similar to the ReactDOM.render() method Our portal now appears above every other piece of content in the app. Below is an image of what our portal looks like in the browser. ![](https://hackmd.io/_uploads/rye5MFOF3.png) ## Use Case of a React Portal React Portals provide a powerful mechanism for rendering components outside the standard React component tree, enabling greater flexibility and control over the DOM structure of your application. There are use cases for ReactPortal; let’s list a few of them. * **Concern division:** Portals can be beneficial for dividing concerns among various components of an application. For instance, you can use a portal to render the video player component outside the main component's DOM hierarchy if your complicated UI component necessitates rendering a distinct component for a particular capability (such as a video player) * **Tooltip and popover components:** By using them, even if the target element is deeply nested within the component tree, the tooltip or popover will always appear in the proper location. * **Overlays and modal dialogs:** Portals are frequently used to make overlays and modal dialogs. No matter where the parent component is in the DOM hierarchy, you can guarantee that the modal component will be rendered at the top level by rendering it via a portal. * **Third-party integrations:** Portals can be used to render the appropriate components at the desired location in the DOM tree when interacting with third-party libraries or widgets that demand a specific DOM structure. ## Best Practices for Building React Portals By following these best practices, you can implement your React Portals effectively and provide the intended functionality while maintaining code clarity and a good user experience. * **Handle events appropriately:** We must make sure that our portal component's event handlers are configured correctly to catch and react to events, even if they take place outside the portal's DOM hierarchy. * **Maintain encapsulation:** To guarantee that the portal component can work properly regardless of where it is in the DOM, avoid relying on external styles or global states. * **Identify the appropriate mounting point:** Choose the proper location in the DOM hierarchy by taking the context and purpose of the component you are presenting into account. * **Consider Accessibility:** A good user experience depends on accessibility. Consider keyboard usability and screen reader compatibility while developing portals. * **Test and debug thoroughly:** Make sure it acts as you would expect it to and doesn't cause any unforeseen problems or conflicts. To find and fix any potential problems, use debugging tools and procedures. ## Conclusion In this article, we have covered how to build a pop-up in React. We first looked at how to build pop-ups the regular way (without using ReactPortals) and then proceeded to build them using Portals. We also discussed the issues developers encountered that led to the introduction of ReactPortals, and how this problem has finally been solved. In my opinion, ReactPortals is the best way to create pop-ups in React. The event delegation and separation of concerns that come with ReactDOM.createPortal() are incredible. I hope you gained knowledge from reading this article. If you get curious and want to further your understanding of React, you can visit [react official website](https://react.dev/blog/2023/03/16/introducing-react-dev) to improve your skills.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully