How to render child component outside of its parent component (DOM Hierarchy) - React.js
Solution 1:
After a quick search, I found React Portal
approach to render child component html outside of the parent component(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>);
};
Portal.js implementation 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>
https://github.com/sedpol/react-portal