Skip to content

Instantly share code, notes, and snippets.

@torressam333
Created January 24, 2024 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torressam333/8480be1811930e34b5e60d862e964e41 to your computer and use it in GitHub Desktop.
Save torressam333/8480be1811930e34b5e60d862e964e41 to your computer and use it in GitHub Desktop.
React Portal Example Implementation
.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";
}
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