React Interview Questions
React.js
FrontendWeb DevelopmentQuestion 38
Explain the concept of portals in React and provide a use case.
Answer:
Portals in React provide a way to render children into a DOM node that exists outside the hierarchy of the parent component. This feature is useful for certain UI patterns that require components to be visually and logically separated from their parent components, such as modals, tooltips, or dropdowns.
How to Create a Portal
To create a portal in React, you use the ReactDOM.createPortal
function, which takes two arguments:
- Children: The React elements you want to render.
- Container: The DOM node into which the children should be rendered.
Syntax
ReactDOM.createPortal(children, container)
Example
Step 1: Create a Portal Component
First, create a component that uses a portal to render its children outside the normal DOM hierarchy.
import React from 'react';
import ReactDOM from 'react-dom';
function PortalExample({ children }) {
const el = document.getElementById('portal-root');
return ReactDOM.createPortal(children, el);
}
export default PortalExample;
Step 2: Use the Portal Component
Next, use the PortalExample
component in your application.
import React, { useState } from 'react';
import PortalExample from './PortalExample';
function App() {
const [showModal, setShowModal] = useState(false);
return (
<div>
<button onClick={() => setShowModal(true)}>Open Modal</button>
{showModal && (
<PortalExample>
<div style={modalStyle}>
<h1>Modal Content</h1>
<button onClick={() => setShowModal(false)}>Close Modal</button>
</div>
</PortalExample>
)}
</div>
);
}
const modalStyle = {
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
padding: '1rem',
backgroundColor: 'white',
border: '1px solid black',
};
export default App;
Step 3: Add the Portal Root to the HTML
Finally, add a div
with the id
of portal-root
to your HTML file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>React Portal Example</title>
</head>
<body>
<div id="root"></div>
<div id="portal-root"></div>
<script src="bundle.js"></script>
</body>
</html>
Use Case for Portals
A common use case for portals is to create modal dialogs. Modals need to be rendered on top of other content and should not be affected by the parent component's styling or overflow properties. By rendering modals in a separate part of the DOM, you can ensure they are properly positioned and styled.
Benefits of Using Portals
- Separation of Concerns: Portals help in keeping the component structure clean by separating UI elements that should not be affected by parent components.
- Styling and Positioning: Portals allow elements like modals and tooltips to be positioned correctly without being constrained by parent components' styles.
- Accessibility: Portals can improve accessibility by ensuring that interactive elements are not hidden or clipped by overflow settings in parent components.
Conclusion
Portals in React provide a powerful way to render components outside the normal DOM hierarchy, making them ideal for use cases such as modals, tooltips, and dropdowns. By understanding and leveraging portals, you can create more flexible and robust user interfaces that handle complex rendering requirements.