I have a problem with the concept of modals in React. When using server side rendered templates with jQuery I was used to have one empty global modal template always available (
One way you can solve this problem by using css and JSX.
this is the app and i can have anything like a button a link anything
Lets assume we have a link (react-router-dom)
which redirects us to
a DeletePage
The Delete Page renders a Modal
You will provide the title
and the actions
of the Modal as props
const App = () => {
return(
SomeAction
)
}
const DeletePage = () => {
return(
history.replace("/")}
action={() => console.log("deleted") }
/>
)
}
const Modal = (props) => {
return(
{props.title}
)
}
- set the
z-index
of the modal a high number
position: fixed
of the modal component
- when the user will click on the background the model will go away (
many ways to implement that like with modal state, redirect, etc i
have taken the redirect as one of the ways )
cancel button
also has the same onClick function which is to dismiss
Delete button
has the action
function passed through props
this method has a flaw because of css because if your parent component
has a position property of relative
then this will break.
The modal will remain inside the parent no matter how high the z-index is
To Save us here comes React-Portal
React portal creates a 'portal' in its own way
The react code you might have will render inside DOM
with id of #root
( in most cases )
So to render our Modal
as the top most layer we create another
DOM element
eg
in the public index.html
file
The Modal
react component code will slightly change
const Modal = (props) => {
return ReactDOM.createPortal(
{props.title}
),document.querySelector("#modal")
}
rest is all the same