Created
January 24, 2024 01:58
-
-
Save torressam333/8480be1811930e34b5e60d862e964e41 to your computer and use it in GitHub Desktop.
React Portal Example Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.alert { | |
position: relative; | |
top: 10px; | |
left: 50%; | |
translate: -50%; | |
background-color: aquamarine; | |
color: black; | |
border-radius: 5px; | |
padding: 10px; | |
cursor: pointer; | |
} | |
#modal-place { | |
border: 2px solid #333; | |
width: 300px; | |
height: 300px; | |
} | |
.container { | |
display: flex; | |
justify-content: space-between; | |
} | |
.left { | |
border: 2px solid #333; | |
width: 300px; | |
height: 300px; | |
} | |
.left::after { | |
content: "LEFT"; | |
} | |
.right { | |
border: 2px solid #333; | |
width: 300px; | |
height: 300px; | |
} | |
.right::after { | |
content: "RIGHT"; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from "react"; | |
import { createPortal } from "react-dom"; | |
import "./App.css"; | |
function App() { | |
const [show, setShow] = useState(false); | |
return ( | |
<div> | |
<h1>Other Content</h1> | |
<button onClick={() => setShow(true)}>Show Message</button> | |
<Alert show={show} onClose={() => setShow(false)}> | |
A sample message to show. | |
<br /> | |
Click it to close. | |
</Alert> | |
<hr /> | |
<p>Some other content</p> | |
<div className="container"> | |
<div className="left"></div> | |
// Content from Alert component will teleport here. Neat! :D | |
<div className="right" id="right"></div> | |
</div> | |
</div> | |
); | |
} | |
const Alert = ({ children, onClose, show }) => { | |
if (!show) return; | |
return createPortal( | |
<div className="alert" onClick={onClose}> | |
{children} | |
</div>, | |
document.getElementById("right") | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment