Typing the Modal Component

In notebook:
FrontEndMasters Intermediate React
Created at:
2019-06-24
Updated:
2019-08-15
Tags:
React libraries JavaScript

https://frontendmasters.com/courses/intermediate-react-v2/typing-the-modal-component/

Starting the migration

The file extension helps doing the migration piece by piece. A starting with Modal.js.

Rename to Modal.tsx.

Let's refactor to TypeScript:

  //    ****        Modal.tsx        ****

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

const modalRoot = document.getElementById("modal");

// **** 1. define the Modal type.  ↴
// const Modal = ({ children }: { children: ReactChild[] }) => {
const Modal: FunctionComponent = ({ children }) => {
// from there, it know that { children } are what (from FunctionComponent)

  // **** 2. don't need to refactor this format
  // it will always be a DIV
  const elRef = useRef(document.createElement("div"));

  useEffect(() => {
    // **** 3. add the if statement.  ↴
    // this will make the errors go away from below
    if (!modalRoot) {
      return;
    }
    modalRoot.appendChild(elRef.current);
    // **** 4. turn this into a function.  ↴
    // that doesn’t return anythig
    // return () => modalRoot.removeChild(elRef.current);
    // use this instead
    return () => {
    // this doesn't return anything
    // so the call signature is OK for TypeScript
      modalRoot.removeChild(elRef.current);
    };
  }, []);

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

export default Modal;