React Udemy #14: Creating Portal with ReactDOM๐Ÿ˜ˆ

JEUNGBIN HANยท2023๋…„ 1์›” 4์ผ

React-Udemy-Lecture

๋ชฉ๋ก ๋ณด๊ธฐ
7/12
post-thumbnail
  1. Make a 'Modal' component
    Inside the Component folder
  2. Make a 'ModalPage' component
    Inside the Page folder
  3. Add route to App.js to show ModalPage when a user goes to '/modal'
<Route path="/modal">
          <ModalPage />
        </Route>
  1. Add a link to the Sidebar component
export default function Sidebar() {
  const links = [
    { label: "Modal", path: "/modal" },
  ];

Toggling Visibility

Parent(button / showModal) => Modal

  • Parent owns state to keep track of whether modal should be displayed
  • Parent component can show a modal at any time for any reason.

About Absolute CSS Rules

inset-0 => top:0; left:0; right:0; bottom:0;

  • If the element is position : absolute
  • the element will expand to fill the height and width
  • Of the colsest parent with a non-stastic positon.
<div>
     <section>
        <div className="absolute inset-0"> Hi </div>
     </section>
</div>

Do not Affecct other elememts/ Using Portals

function Modal(){
  return ReactDOM.createPortal(
    <div>I'm a Modal</div>,
    // Tells React to place HTML produced by this component somewhere else
    document.querySelector('.modal-container')
    //Reference to an element in our index.html file
  )
}

Close Modal

Inside the ModalPage

  const handleClose = () => {
    setShowModal(false);
  };
  
  return (
  <Modal onClose={handleClose}>
  )

Inside the Modal

return (
     <div
        onClick={onClose}
        className="absolute inset-0 bg-gray-300 opacity-80"
      ></div>
)

Customizing the Modal

Inside the ModalPage

  const actionBar = (
    <div>
      <Button onClick={handleClose} primary>
        Acceapt
      </Button>
    </div>
  );

  const modal = (
    <Modal onClose={handleClose} actionBar={actionBar}>
      <p>Here is am inportant agreement for you</p>
    </Modal>
  );

  return (
      {showModal && modal}

Inside the Modal

      <div className="absolute inset-40 p-10 bg-white">
        {children}
        {actionBar}
      </div>

Fix OverFlow


Inside the Modal

export default function Modal({ onClose, children, actionBar }) {
  useEffect(() => {
    document.body.classList.add("overflow-hidden");

    return () => {
      document.body.classList.remove("overflow-hidden");
    };
  }, []);
profile
Web Developer

0๊ฐœ์˜ ๋Œ“๊ธ€