47
rated 0 times
[
54]
[
7]
/ answers: 1 / hits: 18546
/ 4 Years ago, tue, may 12, 2020, 12:00:00
I'm trying to make an overlay that will appear when I clicked the menu button and close when clicked anywhere on the page. But nothing is happening when I clicked the button.
I'm still new to React Hooks, so I hope you'll understand if I make obvious mistakes.
Here are my codes:
App.js
import React from react;
import ReactDOM from react-dom;
import ./styles.css;
const modalRoot = document.getElementById(modal-root);
const Modal = props => {
return ReactDOM.createPortal(
<div className=overlay>{props.children}</div>,
modalRoot
);
};
export default function App() {
const [open, setOpen] = React.useState(false);
return (
<div className=App>
<button onClick={() => setOpen(!open)}>Menu</button>
{open && <Modal in={open}>Click anywhere to close</Modal>}
</div>
);
}
App.css
body {
font-family: sans-serif;
}
.App {
position: relative;
text-align: center;
}
* {
box-sizing: border-box;
}
.overlay {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
cursor: pointer;
}
Here's a link to CodeSandbox
More From » css