React Portals: A Beginner's Guide to Mastering the Art of Dynamic Components
React is a powerful JavaScript library for building user interfaces, but it has one limitation: all elements rendered by a React component must be children of the component's parent DOM node. However, there are certain cases where you may want to render a component outside of its parent. For example, you may want to create a modal dialog that appears on top of the rest of the content, or a tooltip that follows the mouse cursor.
React portals provide a way to solve this problem by allowing you to render a component into a different DOM node, outside of its parent. In this guide, we'll take a look at what portals are, how they work, and how to use them to create common UI elements like modals, tooltips, and more.
First, let's define what portals are. In React, a portal is a way to render a component into a different DOM node than its parent. This is done using the ReactDOM.createPortal()
function, which takes two arguments: the React component to be rendered and the DOM node where it should be rendered.
Here's an example of how to use portals to create a modal dialog. In this example, we have a Modal
component that renders a dialog box with a title, some content, and a close button. We want to render this component on top of the rest of the content, so we'll use a portal to render it into a div
element with an id
of "modal-root".
import React from 'react';
import ReactDOM from 'react-dom';
class Modal extends React.Component {
render() {
return ReactDOM.createPortal(
<div>
<h1>Modal Title</h1>
<p>Modal Content</p>
<button>Close</button>
</div>,
document.getElementById('modal-root')
);
}
}
In this example, we're using the createPortal
function to render the Modal
component into a DOM node with an id
of "modal-root". This means that the modal will appear on top of the rest of the content, as if it were a separate page.
Now let's look at how to use portals to create a tooltip. In this example, we have a React's portals are a powerful tool that allows developers to render a component outside of its parent component's DOM tree. This can be useful in a variety of situations, such as when you need to create a modal, a tooltip, or a floating menu. In this blog post, we will take a look at what portals are, how they work, and some examples of how you can use them to enhance your React applications.
One of the key benefits of portals is that they allow you to render a component in a different location in the DOM without having to re-render the entire parent component. This is achieved by creating a new "root" DOM node, which is separate from the parent component's DOM tree. This new root node acts as a container for the portal component, and the portal component is then rendered inside of this container.
To create a portal in React, you will need to use the createPortal
function, which is exported from the react-dom
package. This function takes two arguments: the component you want to render, and the DOM node where you want to render it. Here's an example of how you would use the createPortal
function to create a modal:
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(children, document.getElementById('modal-root'));
}
In this example, we are using the createPortal
function to render the children
prop inside of the #modal-root
DOM node. You will also need to create this DOM node somewhere in your HTML file, like this:
<div id="modal-root"></div>
Now, you can use the Modal
component in your application and it will be rendered inside of the #modal-root
DOM node.
Another use case for portals is creating a tooltip. The following example demonstrates how to create a tooltip that appears when the user hovers over a button.
import { createPortal } from 'react-dom';
class Tooltip extends React.Component {
state = {
show: false
};
toggleShow = () => {
this.setState(prevState => ({ show: !prevState.show }));
};
render() {
const { children, message } = this.props;
return (
<React.Fragment>
{children(this.toggleShow)}
{this.state.show && createPortal(<div>{message}</div>, document.body)}
</React.Fragment>
);
}
}
export default Tooltip;
// Usage:
// <Tooltip message="This is the tooltip message">
// {(toggleShow) => <button onMouseEnter={toggleShow} onMouseLeave={toggleShow}>Hover me</button>}
// </Tooltip>
// in the above example, when the button is hovered, the state of show is toggled, and the tooltip message is rendered through the portal to the document body.
As you can see, portals are a powerful tool in the React developer's toolkit. They allow you to escape the constraints of the DOM tree and render content in a different location on the page. This can be especially useful when dealing with modals, tooltips, or other UI elements that need to be rendered outside of the component hierarchy.
To use portals in your own React application, you'll need to first import the createPortal
function from the react-dom
package. Once you've done that, you can use it to create a portal by passing in the JSX elements you want to render, as well as the DOM node that you want to render them into.
Here's an example of how you might use portals to create a modal in your application:
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal">
{children}
</div>,
document.body
);
}
function App() {
return (
<div>
<button onClick={() => setIsModalOpen(true)}>Open Modal</button>
{isModalOpen && <Modal>Hello, I'm a modal!</Modal>}
</div>
);
}
As you can see, portals are a powerful tool in the React developer's toolkit. They allow you to escape the constraints of the DOM tree and render content in a different location on the page. This can be especially useful when dealing with modals, tooltips, or other UI elements that need to be rendered outside of the component hierarchy.
To use portals in your own React application, you'll need to first import the createPortal function from the react-dom package. Once you've done that, you can use it to create a portal by passing in the JSX elements you want to render, as well as the DOM node that you want to render them into.
Here's an example of how you might use portals to create a modal in your application:
import { createPortal } from 'react-dom';
function Modal({ children }) {
return createPortal(
<div className="modal">
{children}
</div>,
document.body
);
}
function App() {
return (
<div>
<button onClick={() => setIsModalOpen(true)}>Open Modal</button>
{isModalOpen && <Modal>Hello, I'm a modal!</Modal>}
</div>
);
}
You can use portals to create a wide variety of UI elements, such as tooltips, dropdowns, and even entire pages or sections of your application. They are a powerful tool that can help you create more dynamic, flexible, and reusable components.
In conclusion, portals can be a great way to add some extra functionality and flexibility to your React applications. They are a powerful tool that can help you create more dynamic and reusable components, and they can be used to create a wide variety of UI elements. With the right approach, portals can help you create a more efficient, effective and user-friendly React.
Thanks for reading my post on "React Portals: A Beginner's Guide to Mastering the Art of Dynamic Components"! I hope you found it informative and helpful. If you want to stay updated, be sure to follow me on Twitter at @abhaysinghr1.
Also, I am excited to announce that I have created a product "500+ Best AI Tools & Prompts" which is completely free and can be downloaded on gumroad https://abhaysinghr1.gumroad.com/l/otdpdo. It contains a curated list of the best AI tools and prompts to help you enhance your writing process. I hope you find it useful and it helps you to take your writing to the next level.
Thank you for reading and happy writing!
Subscribe to my newsletter
Read articles from Abhay Singh Rathore directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Abhay Singh Rathore
Abhay Singh Rathore
A software engineer specializing in building (and occasionally designing) exceptional websites, applications, and everything in between.