Skip to content

Instantly share code, notes, and snippets.

@braska
Created May 22, 2019 19:26
Show Gist options
  • Save braska/0c64f761de13f913acc0cda522412734 to your computer and use it in GitHub Desktop.
Save braska/0c64f761de13f913acc0cda522412734 to your computer and use it in GitHub Desktop.
React Portals
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import styled, { css } from 'styled-components';
import { rgba } from 'polished';
const Wrapper = styled.div`
position: absolute;
z-index: 10000;
&::before {
content: '';
position: fixed;
display: block;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: ${({ theme }) => rgba(theme.colors.neutral1, 0.65)};
z-index: 1;
}
`;
export default class Overlay extends Component {
static propTypes = {
children: PropTypes.node,
};
el = typeof document !== 'undefined' && document.createElement('div');
componentDidMount() {
document.body.appendChild(this.el);
}
componentWillUnmount() {
document.body.removeChild(this.el);
}
render() {
return ReactDOM.createPortal(
<Wrapper>
{this.props.children}
</Wrapper>,
this.el,
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment