Explain React Portals Vs Forward Ref? See Example

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

FeaturePortalsForward Ref
PurposeRender outside DOM hierarchyPass ref from parent to child
Use CaseModals, tooltips, overlaysAccess child DOM elements
DOM PlacementOutside parentInside normal hierarchy
Component TypeAny JSXFunctional 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

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *