- ReactJS Tutorial
- ReactJS - Home
- ReactJS - Introduction
- ReactJS - Installation
- ReactJS - Features
- ReactJS - Advantages & Disadvantages
- ReactJS - Architecture
- ReactJS - Creating a React Application
- ReactJS - JSX
- ReactJS - Components
- ReactJS - Nested Components
- ReactJS - Using Newly Created Components
- ReactJS - Component Collection
- ReactJS - Styling
- ReactJS - Properties (props)
- ReactJS - Creating Components using Properties
- ReactJS - props Validation
- ReactJS - Constructor
- ReactJS - Component Life Cycle
- ReactJS - Event management
- ReactJS - Creating an Event−Aware Component
- ReactJS - Introduce Events in Expense Manager APP
- ReactJS - State Management
- ReactJS - State Management API
- ReactJS - Stateless Component
- ReactJS - State Management Using React Hooks
- ReactJS - Component Life Cycle Using React Hooks
- ReactJS - Layout Component
- ReactJS - Pagination
- ReactJS - Material UI
- ReactJS - Http client programming
- ReactJS - Form Programming
- ReactJS - Controlled Component
- ReactJS - Uncontrolled Component
- ReactJS - Formik
- ReactJS - Conditional Rendering
- ReactJS - Lists
- ReactJS - Keys
- ReactJS - Routing
- ReactJS - Redux
- ReactJS - Animation
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - Table
- ReactJS - Managing State Using Flux
- ReactJS - Testing
- ReactJS - CLI Commands
- ReactJS - Building and Deployment
- ReactJS - Example
- Hooks
- ReactJS - Introduction to Hooks
- ReactJS - Using useState
- ReactJS - Using useEffect
- ReactJS - Using useContext
- ReactJS - Using useRef
- ReactJS - Using useReducer
- ReactJS - Using useCallback
- ReactJS - Using useMemo
- ReactJS - Custom Hooks
- ReactJS Advanced
- ReactJS - Accessibility
- ReactJS - Code Splitting
- ReactJS - Context
- ReactJS - Error Boundaries
- ReactJS - Forwarding Refs
- ReactJS - Fragments
- ReactJS - Higher Order Components
- ReactJS - Integrating With Other Libraries
- ReactJS - Optimizing Performance
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - React Without ES6 ECMAScript
- ReactJS - React Without JSX
- ReactJS - Reconciliation
- ReactJS - Refs and the DOM
- ReactJS - Render Props
- ReactJS - Static Type Checking
- ReactJS - Strict Mode
- ReactJS - Web Components
- Additional Concepts
- ReactJS - Date Picker
- ReactJS - Helmet
- ReactJS - Inline Style
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - Carousel
- ReactJS - Icons
- ReactJS - Form Components
- ReactJS - Reference API
- ReactJS Useful Resources
- ReactJS - Quick Guide
- ReactJS - Useful Resources
- ReactJS - Discussion
ReactJS - createPortal() Method
React portals allow us to move portions of our website to a different location on the screen. They are useful for a variety of activities, like displaying pop-up boxes or inserting material into a specific section of a page.
The createPortal is a React function that allows us to move items around on our website. Assume we have a box on our website and we want something to appear in a different location on the page within that box. This is where createPortal comes into picture.
Syntax
<div> <MyComponent /> {createPortal(children, domNode, key!)} </div>
Parameters
children − Anything we want to display, like text, a picture, or another section of our website.
domNode − The location on the page where we wish our content to appear. It might be the entire page or just a portion of it.
Optional key − It is an additional code that will help React in keeping track of things. This is normally left empty.
Return Value
When we use createPortal, we get something special in return. This special object is similar to a magic card that we can insert into our code and React will know where to display our content.
Examples
Let us see different examples of createPortal by creating small React applications.
Example 1
This app shows a button. When we click the button, a special window called a "modal" shows on the screen. The modal is like a small box that contains some information or options. We can close the modal by clicking a small "x" inside it.
AppModal.js
import React from 'react'; import { createPortal } from 'react-dom'; const AppModal = ({ isOpen, onClose }) => { const modalRoot = document.getElementById('modal-root'); if (!modalRoot) { console.error("Modal root container not found in the DOM."); return null; } return isOpen ? createPortal( <div className="modal App"> <div className="modal-content"> <span className="close" onClick={onClose}>×</span> <p>This is a modal!</p> </div> </div>, modalRoot ) : null; }; export default AppModal;
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <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 App</title> </head> <body> <div id="root"></div> <div id="modal-root"></div> </body> </html>
App.js
import React, { useState } from 'react'; import AppModal from './AppModal'; import './App.css'; const App = () => { const [modalOpen, setModalOpen] = useState(false); const handleOpenModal = () => setModalOpen(true); const handleCloseModal = () => setModalOpen(false); return ( <div className='App'> <h1>Modal</h1> <button onClick={handleOpenModal}>Open Modal</button> <AppModal isOpen={modalOpen} onClose={handleCloseModal} /> </div> ); }; export default App;
Output
There is a button that called "Open Modal." When we click the button, a modal appears with a message inside it. To close the modal, we can click the "x" on the left side.
Example 2
This app has a button, and when we hover our mouse over the button, a small box with extra information appears. This small box is called a "tooltip." It gives us more details about the button.
AppTooltip.js
import React from 'react'; import { createPortal } from 'react-dom'; import './App.css'; const AppTooltip = () => { const tooltipRoot = document.getElementById('tooltip-root'); if (!tooltipRoot) { console.error("Tooltip root container not found in the DOM."); return null; } return createPortal( <div className="tooltip App"> <p>This is a tooltip!</p> </div>, tooltipRoot ); }; export default AppTooltip;
index.html
<!DOCTYPE html> <html lang="en"> <head> <title>React App</title> </head> <body> <div id="root"></div> <div id="tooltip-root"></div> </body> </html>
App.js
import React from 'react'; import AppTooltip from './AppTooltip'; import './App.css'; const App = () => { return ( <div className='App'> <h1>Tooltip App</h1> <button>Hover me</button> <AppTooltip /> </div> ); }; export default App;
Output
There is a button that we can hover our mouse over. When we hover over the button, a little box with information appears. This box is the tooltip, and it disappears when we move our mouse away.
Example 3
In this app, there is a special component that seems to float on the page. It is like a small box with information that stays in one place even when we scroll the page. This can be useful for important details we want people to always see.
AppFloatingComponent.js
import React from 'react'; import { createPortal } from 'react-dom'; const AppFloatingComponent = () => { const floatingRoot = document.getElementById('floating-root'); return createPortal( <div className="floating-component"> <p>This is a floating component!</p> </div>, floatingRoot ); }; export default AppFloatingComponent;
index.html
<div id="floating-root"></div>
App.js
import React from 'react'; import AppFloatingComponent from './AppFloatingComponent'; import './App.css'; const App = () => { return ( <div className='App'> <h1>Floating Component</h1> <AppFloatingComponent /> </div> ); }; export default App;
Output
There is a box with information that stays in one place on the page. Even if we scroll up or down, the box remains visible.
This can be handy for showing important information that we want people to see all the time.
Limitations
When using portals, events ( like clicking) can happen differently. If we find problems we can either resolve them from within the portal or relocate the portal within our webpage family.
Summary
React portals are like magical doors that let us better structure our website. With createPortal, we are able to rearrange elements to make our website seem exactly how we want it to.
To Continue Learning Please Login
Login with Google