Skip to content

Instantly share code, notes, and snippets.

@gregberge
Last active March 27, 2019 14:57
Show Gist options
  • Save gregberge/2355b23411c188a4b188ce5d947f3046 to your computer and use it in GitHub Desktop.
Save gregberge/2355b23411c188a4b188ce5d947f3046 to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import styled from 'styled-components'
const Backdrop = styled.div`
position: absolute;
background-color: rgba(0, 0, 0, 0.5);
top: 0;
right: 0;
bottom: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
`
const Modal = styled.div`
font-size: 20px;
text-align: center;
color: white;
width: 500px;
background-color: #222;
padding: 10px;
`
function useContainer() {
const [container, setContainer] = useState(null)
useEffect(() => {
const container = document.createElement('div')
document.body.appendChild(container)
setContainer(container)
return () => {
document.body.removeChild(container)
}
}, [setContainer])
return container
}
function useBlockScroll() {
useEffect(() => {
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = 'visible'
}
}, [])
}
function Portal({ children }) {
const container = useContainer()
return container ? createPortal(children, container) : null
}
export default function About({ history }) {
useBlockScroll()
return (
<Portal>
<Backdrop onClick={() => history.push('/')}>
<Modal>Hello !</Modal>
</Backdrop>
</Portal>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment