# Portals and Refs

Setting up a separate mount point

* Modify index.html and add another div to become a separate mount point for portal.&#x20;

```html
<!-- above #root -->
<div id="modal"></div>
```

* Create a modal component.&#x20;
* Implement useRef to maintain a reference to the portals DOM element.&#x20;
* Utilize useEffect for cleanup.

```jsx
import React, { useEffect, useRef } from "react";
import { createPortal } from "react-dom";

const Modal = ({ children }) => {
  // Implement useRef to maintain a reference to the portals DOM element. 
  const elRef = useRef(null);
  if (!elRef.current) {
    elRef.current = document.createElement("div");
  }

  // Utilize useEffect for cleanup.
  useEffect(() => {
    const modalRoot = document.getElementById("modal");
    modalRoot.appendChild(elRef.current);
    return () => modalRoot.removeChild(elRef.current);
  }, []);

  return createPortal(<div>{children}</div>, elRef.current);
};

export default Modal;

```

Implementing Modal

* Import modal to Details.jsx&#x20;
* Utilize useState hook to control the visibility of the modal.&#x20;
* Show the modal when the button is clicked.

```jsx
// at the top
import { useState } from "react";
import Modal from "./Modal";

// add showModal
const [showModal, setShowModal] = useState(false);

// add onClick to <button>
<button onClick={() => setShowModal(true)}>Adopt {pet.name}</button>;

// below description
{
  showModal ? (
    <Modal>
      <div>
        <h1>Would you like to adopt {pet.name}?</h1>
        <div className="buttons">
          <button>Yes</button>
          <button onClick={() => setShowModal(false)}>No</button>
        </div>
      </div>
    </Modal>
  ) : null;
}
```
