Unlock the Power of React Portals
When working with React, you’re likely familiar with the limitation of rendering HTML elements under a single div tag with an ID of root. This constraint can be frustrating when trying to render elements outside the root node, such as modals or tooltips. Fortunately, React portals were introduced in version 16.0 to solve this issue.
What are React Portals?
React portals allow you to render elements outside the root node, providing more flexibility in your component design. However, working with portals can be verbose and cumbersome.
Introducing react-cool-portal
react-cool-portal is a lightweight library (~ 1.4KB gzipped) that provides a simple and efficient way to work with portals. With its Hooks-based API, you can easily create and manage portals, leveraging features like state controllers, event listeners, and server-side rendering compatibility.
Key Features of react-cool-portal
- Render elements to a default element in the
<body>
or a specified DOM element - Flexibly handle portals with state controllers and event listeners
- Use as a wrapper to build custom Hooks
- Automatically removes unused portal containers
- Supports TypeScript type definitions
Building an Animated Modal with react-cool-portal
Let’s build a simple animated modal using react-cool-portal. We’ll create a button that, when clicked, will display an animated modal. We can then exit the modal from the modal itself.
import { useState } from 'eact';
import { usePortal } from 'eact-cool-portal';
function App() {
const [showModal, setShowModal] = useState(false);
const { Portal } = usePortal({
defaultElement: document.body,
});
const handleShowModal = () => {
setShowModal(true);
};
return (
{showModal && (
)}
);
}
In this example, we create a piece of state to render the Portal component depending on whether the button has been clicked. We then define two animations: slideIn and slideOut.
.modal {
animation: slideIn 0.5s forwards;
}
@keyframes slideIn {
0% {
transform: translateY(-100%);
}
100% {
transform: translateY(0);
}
}
@keyframes slideOut {
0% {
transform: translateY(0);
}
100% {
transform: translateY(-100%);
}
}
With react-cool-portal, you can create custom Hooks for code reusability and simplify your portal management. Explore the library’s features and build your own animated modal today!