Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
45

In your styles.css, you are setting the CSS display property to none. This should be changed to display: block.



The Modal will then be only displayed when the value of open is true.


[#50959] Thursday, April 30, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianom

Total Points: 601
Total Questions: 98
Total Answers: 109

Location: Kenya
Member since Fri, Dec 23, 2022
1 Year ago
lucianom questions
Tue, Feb 22, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Sun, Jan 24, 21, 00:00, 3 Years ago
Sat, Aug 15, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;