Horje
Provide an Example Scenario where Portals are Useful in React

React Portals offer a powerful solution for rendering components outside the typical DOM hierarchy, without disrupting the natural flow of events within the React component tree. This capability is particularly beneficial for creating UI elements like modals, tooltips, and notification popups, which require placing outside the immediate parent component’s scope. React Portals ensure that these components function correctly, regardless of their position in the DOM hierarchy, thereby enhancing the overall user interface design and functionality.

Prerequisites

Steps to Create a React App

Step 1: Setup Your React Application

  • Initialize a new React project using create-react-app or your preferred setup method.
  • Ensure you have React Router installed if you plan to navigate between pages.
npx create-react-app portal-example
cd portal-example
npm start

Step 2: Create a Basic Component Structure

  • Start with a simple layout component that includes a button to trigger the modal.
  • Implement a Modal component that will be rendered using React Portal.

Step 3: Implementing React Portal for Modal

  • Import ReactDOM.createPortal() from react-dom.
  • Use createPortal() to render the Modal component into a div element placed outside the main component tree (e.g., at the root level of your HTML file).

Example: This is the code for App.js file for creating a modal.

JavaScript
// App.js
import React, { useState } from 'react';
import ReactDOM from 'react-dom';
import './App.css';

function App() {
    const [isModalOpen, setIsModalOpen] = useState(false);

    return (
        <div className="App">
            <button onClick={() =>
                setIsModalOpen(true)}>Open Modal
            </button>
            {isModalOpen && ReactDOM.createPortal(
                <Modal onClose={() => setIsModalOpen(false)} />,
                document.getElementById('portal-root')
            )}
        </div>
    );
}

function Modal({ onClose }) {
    return (
        <div style=
            {{
                position: 'fixed',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)'
            }}>
            <h1>Modal Title</h1>
            <p>This is a modal dialog.</p>
            <button onClick={onClose}>Close</button>
        </div>
    );
}

export default App;

In your index.html, add a div with the id portal-root:

HTML
<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" 
          href="/vite.svg" />
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0" />
    <title>Vite + React</title>
</head>

<body>
    <div id="root"></div>
    <div id="portal-root"></div>
    <script type="module" src="/src/main.jsx"></script>
</body>

</html>

Output: When you click the “Open Modal” button, the modal dialog box will appear centered on the screen, overlaying other content. The modal is rendered outside the main component tree, demonstrating the utility of React Portals.

Recording-2024-03-09-224618

Output




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
Add Styling to defaultValue in textarea in React Add Styling to defaultValue in textarea in React
What is NativeRouter in React Router? What is NativeRouter in React Router?
How to Access Files Uploaded to hte Public Folder in Next.js? How to Access Files Uploaded to hte Public Folder in Next.js?
ReactJS Evergreen ReactJS Evergreen
React Rebass React Rebass

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18