I'm dealing with a weird issue concerning modals/portals in React.js.
The issue is that the modal is not appearing as a pop-up over the other elements of the screen. I've been going through documentation but I can't spot my mistake.
The code below is for the modal called "SignIn" as well as the "App" files.
SignIn.js
import React from "react";
import ReactDOM from "react-dom"
const SignIn =({message,isopen,onclose})=>{
if(!isopen) return null;
return ReactDOM.createPortal(
<div className="modal">
<h2>{message}</h2>
<button onClick={onclose}>Close</button>
</div>,
document.body
);
};
export default SignIn;
App.js
import SignIn from "./Components/Modal/SignIn";
const App = ()=>{
const [currentPaneName, setCurrentPaneName]=useState("MainPane");
const [modalOpen, setModalOpen]=useState(false);
return(
<React.Fragment>
<Header onNewPaneSelected={updateCurrentPane} />
<div>
<SignIn
message="This is a test modal"
isopen={modalOpen}
onclose={()=>setModalOpen(false)}
/>
</div>
<main>
<button onClick={()=>setModalOpen(true)}>Open Modal</button>
<LoadPaneHandler />
</main>
{/* <Footer /> */}
</React.Fragment>
);
}
export default App;
I've omitted code that wasn't relevant so that's why things may seem missing.
The result of this when I run the website is this...
The button to open the modal appears but when it is clicked, it opens the text and the button to close it at the bottom of the screen and not over the other contents like a modal should. All of the other UI elements are completely usable while this is happening.
As I said, I've gone over this issue quite a few times and I can't spot my mistake. Any pointers would be greatly appreciated!
I discovered the cause. I thought that only the Javascript code was needed to create a functional modal. Once I added a CSS file that specified elements such as...
The modal began to work exactly as it should! I'm not sure why I believed that it would work without this but I was clearly mistaken.
Here's an example of the CSS I used to make this work.
.modal {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
background-color: rgb(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
}
I've also included a picture of the modal at work. Please ignore the ugly colors, they're placeholder while I experiment.