Skip to content

Instantly share code, notes, and snippets.

@amikitevich
Last active May 3, 2020 03:02
Show Gist options
  • Save amikitevich/7d60d179334bda19add9cb359b74daf7 to your computer and use it in GitHub Desktop.
Save amikitevich/7d60d179334bda19add9cb359b74daf7 to your computer and use it in GitHub Desktop.
Wrapper around React's portal
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#app-root {
width: 100%;
height: 100%;
position: relative;
z-index: 1;
}
#modal-root {
position: relative;
z-index: 2;
}
</style>
</head>
<body>
<div id="app-root"></div>
<div id="modal-root"></div>
</body>
</html>
import { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
const modalRoot = document.getElementById('modal-root');
// Let's create a Modal component that is an abstraction around
// the portal API.
class InPortal extends Component {
constructor(props) {
super(props);
// Create a div that we'll render the modal into. Because each
// Modal component has its own element, we can render multiple
// modal components into the modal container.
this.el = document.createElement('div');
}
componentDidMount() {
// Append the element into the DOM on mount. We'll render
// into the modal container element (see the HTML tab).
modalRoot.appendChild(this.el);
}
componentWillUnmount() {
// Remove the element from the DOM when we unmount
modalRoot.removeChild(this.el);
}
render() {
// Use a portal to render the children into the element
return ReactDOM.createPortal(
// Any valid React child: JSX, strings, arrays, etc.
this.props.children,
// A DOM element
this.el,
);
}
}
InPortal.propTypes = {
children: PropTypes.any,
};
export default InPortal;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment