React Portals vs Forward Ref
Both React Portals and Forward Ref deal with DOM elements, but they serve different purposes:
- Portals: Render children into a DOM node outside the parent hierarchy
- Forward Ref: Pass a ref from parent to child to access DOM elements
React Portals Example
import React from "react";
import ReactDOM from "react-dom";
function Modal() {
return ReactDOM.createPortal(
<div className="modal">This is a portal modal!</div>,
document.getElementById("modal-root")
);
}
function App() {
return (
<div>
<h1>React Portals</h1>
<Modal />
</div>
);
}
✅ Renders modal outside parent DOM node.
React Forward Ref Example
import React, { useRef } from "react";
const Input = React.forwardRef((props, ref) => <input ref={ref} />);
function App() {
const inputRef = useRef();
return (
<div>
<Input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
</div>
);
}
✅ Parent can directly access child input element.
Key Differences
| Feature | Portals | Forward Ref |
|---|---|---|
| Purpose | Render outside DOM hierarchy | Pass ref from parent to child |
| Use Case | Modals, tooltips, overlays | Access child DOM elements |
| DOM Placement | Outside parent | Inside normal hierarchy |
| Component Type | Any JSX | Functional components only |
Conclusion
Portals are for DOM placement outside the parent, while Forward Ref is for parent access to child DOM. Both enhance React flexibility.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP