Rendering a child component beyond the confines of its parent component in React.js: A Step-by-Step Guide

I am working with a table component that has sticky headers and dropdowns, ellipsis menus, and other complex components within the table body rows. Each row of the table contains nested table body rows, and the parent rows stick to their child rows. However, the dropdowns and ellipsis menus get hidden behind the next sticky row due to z-index limitations. The only solution is to render these menus outside of the table with a higher z-index.

For easier understanding, let's consider the render method:

return <div id='parent'>
            <input />
            <span id='child'>{value}</span>
       </div>;

I aim to render child outside of parent in DOM Hierarchy as follows:

...
<body>
    <div id='parent'> <input /> </div>
    <div id='child'></div>
<body>
...

Answer №1

After conducting a brief search, I came across the use of React Portal approach to render child component HTML outside of the parent component within the DOM Hierarchy.

Component:

import React, { useState } from 'react';
import { Portal } from '../Portal/Portal';


export const FirstPage = () => {

const [value, setValue] = useState('');

return (
    <div id='parent'>
        <input onChange={e => {setValue(e.target.value)}} value={value} />
        <Portal>
            <span id='child'>{value}</span>
        </Portal>
    </div>);
};

Implementing Portal.js with React Hooks:

import React, { useEffect, useRef } from "react"
import ReactDOM from 'react-dom';

export const Portal = (props) => {
    const el = useRef(document.createElement('div'));
    useEffect(() => {
        const portal = document.getElementById('portal');
        portal.appendChild(el.current);

        return () => {
            portal.removeChild(el.current);
        };

    }, [props.children]);

    return ReactDOM.createPortal(props.children, el.current);
}

export const PortalDiv = () => <div id='portal'></div>;

App.js:

import React from 'react';
import './App.css';
import { PortalDiv } from './Portal/Portal';
import { FirstPage } from './Pages/FirstPage';

function App() {
  return (
    <div className="App">
      <FirstPage />
      <PortalDiv />
    </div>
  );
}

export default App;

Result:

<div class="App">
    <div id="parent">
        <input value="random text">
    </div>
    <div id="portal">
        <div><span id="child">random text</span></div>
    </div>
</div>

For more information and examples, visit: https://github.com/sedpol/react-portal

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to fetch data in CakePHP 3.x controller using jQuery AJAX POST

I've been searching everywhere and unfortunately, I can't seem to figure out why the data is not being sent to my controller when posting via ajax. Here's the jQuery code snippet: var newDate = {}; newDate['start' ...

What is the process to enable a tab in AngularJS using Foundation's tab feature?

Currently, I am utilizing AngularJS in conjunction with Foundations. Visit the official website for more information Within my page, there are two tabs that are functioning correctly as shown below: <tabset> <tab heading="tab1"> </tab ...

Tips for storing quiz results in a database with commas as separators:

I have a quiz script that presents multiple-choice questions. After logging in, the user can answer 10 questions per quiz session. At the end of the quiz, the results are saved into a database in the following format: id category_name user_id question_ ...

Issues with Javascript functionality on aspdotnetstorefront site

Lately, I've been facing some challenges with my Javascript and jQuery codes when trying to implement them in the storefront. Despite attempting different methods to create a slider, none seem to work within the store environment - even though they fu ...

Having trouble with PHP Storm and Vue component not working? Or encountering issues with unresolved function or method in your

I have been struggling with this issue for days and cannot seem to find a solution online. Being new to Vue.js, I am currently working on a TDD Laravel project: My goal is to add the standard Vue example-component to my app.blade.php as follows: app.bla ...

Platform designed to simplify integration of high-definition imagery and scalable vector illustrations on websites

In the ever-evolving world of technology, some clients support advanced features like svg while others do not. With the rise of high resolution devices such as iPhone 4+ and iPad 3rd gen., it has become crucial to deliver graphics that can meet these stand ...

How can I alter the font color of the parent <li> tag when the child <li> tag is being hovered over using CSS?

CSS Question: <ul> <li>LINK 1</li> <li>LINK 2</li> <li>LINK 3 <ul> <li>link 3.1</li> <li>link 3.2</li> </ul> </li> </ul> Is there a way in CSS to change the t ...

Creating a dropdown menu that includes miniature images: A step-by-step guide

Specifics I am interested in incorporating a small flag to the left of my dropdown menu. I need guidance on the recommended method for achieving this. My Attempt So Far <!-- Dropdown-Menu --> <div class="col-sm-6 drop-down "> S ...

Container displaying zero height due to masonry issue

Currently, I am developing a project that requires a responsive masonry layout. The container has a maximum width set to 960px, but it is supposed to adjust based on the browser's size. Each grid item has a percentage-based width (100%, 66.666666etc%, ...

Dynamically injecting divs into a webpage's left side using JavaScript

Currently, the div's are being added from the left side and moving to the right. How can I change it so that the div's are added from the left? This way, the first card will appear in the middle and new cards will stack up behind it to the left. ...

Issue encountered in React 18: The value on the left side of an assignment statement must be a variable or a property that can be accessed

After upgrading my React version from 17 to 18, I encountered an error with this code: data?.area?.width=['111','220']. The error message states "The left-hand side of an assignment expression must be a variable or a property access." W ...

Updating the parent component of a Vue router when closing nested routes

I have a scenario where I encounter the following steps: Go to the /parent page and see the Parent component being displayed Proceed to /parent/john and witness the Child component being rendered Return back to /parent and observe the child component bei ...

An issue has occurred in React Redux where the page is loading before retrieving the necessary data

I've encountered a frustrating issue where I need to retrieve data before the DOM loads, but I keep running into a persistent error. Despite receiving a 200 response on my query, the error persists until I reload the page. The display is fine after th ...

Display column header row divider for pinned columns in v5 DataGrid

I'm attempting to customize the appearance of pinned columns in MUI's DataGrid by adding a column header-row divider. The official demo by MUI for pinned columns [https://codesandbox.io/s/qix39o?file=/demo.tsx] displays the pinned column header ...

Navigate to the chosen item in material-ui scroll bar

Currently, I have a list created using material-ui which contains numerous items and displays a scrollbar due to its size. I am looking for a way to automatically scroll to the selected item within the list. Does anyone have any suggestions on how I can a ...

the three.js code runs smoothly on JSfiddle, but it does not seem to be working properly

Check out this basic three.js code snippet for generating custom geometry http://jsfiddle.net/67Lgzjpb/. After attempting to run this code directly in my browser (not via JSFiddle), an error message pops up: TypeError: geom.computeCentroids is not a funct ...

What is the best way to showcase a chart using jquery?

Is there a way to incorporate trendlines or target lines in highcharts similar to fusion chart? I have been able to draw them successfully in fusion charts. Check out this fiddle link: http://jsfiddle.net/Tu57h/139/ I attempted to recreate the same in hi ...

Is it possible to utilize two nested routes in React Router Dom v6 while using the colon symbol ( : )?

I launched a new react website called My Website Take a look at my website for better understanding In the blog section, I implemented two nested routes <Route path="/blog" element={<Blog />} > <Route path="" e ...

JavaScript code for sending information to the server

I am attempting to write data to a file on the server when a user clicks on a button, using JavaScript. I followed the method outlined in this Stack Overflow post: Saving a text file on server using JavaScript. Unfortunately, it did not work as expected. ...

The right padding on an HTML table is not functioning properly when the table width is larger than

I am facing an issue with a table that has multiple columns. I want each column to have the same width, resulting in the total table width being wider than the page width. This is fine as it prompts the browser to display a horizontal scrollbar. However, d ...