简体   繁体   中英

How to create an overlay with React?

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

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 .

you probably found the answer already but you'll need to change your display: none to display: block and then use visibility: hidden (when the modal is closed) and visibility: visible when the modal is open

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM