create portal root for toast on demand

This commit is contained in:
Sebastian Sdorra
2019-12-12 10:20:50 +01:00
parent 3c615bc7ba
commit a973529328
4 changed files with 37 additions and 6 deletions

View File

@@ -1,2 +0,0 @@
<div id="modalRoot"></div>
<div id="toastRoot"></div>

View File

@@ -2,14 +2,13 @@ import React, { FC } from "react";
import { createPortal } from "react-dom";
import styled from "styled-components";
import { getTheme, Themeable, ToastThemeContext, Type } from "./themes";
import usePortalRootElement from "../usePortalRootElement";
type Props = {
type: Type;
title: string;
};
const rootElement = document.getElementById("toastRoot");
const Container = styled.div<Themeable>`
z-index: 99999;
position: fixed;
@@ -43,8 +42,10 @@ const Title = styled.h1<Themeable>`
`;
const Toast: FC<Props> = ({ children, title, type }) => {
const rootElement = usePortalRootElement("toastRoot");
if (!rootElement) {
throw new Error("could not find toast container #toastRoot");
// portal not yet ready
return null;
}
const theme = getTheme(type);

View File

@@ -0,0 +1,33 @@
import { useEffect, useState } from "react";
const createElement = (id: string) => {
const element = document.createElement("div");
element.setAttribute("id", id);
return element;
};
const appendRootElement = (rootElement: HTMLElement) => {
document.body.appendChild(rootElement);
};
const usePortalRootElement = (id: string) => {
const [rootElement, setRootElement] = useState<HTMLElement>();
useEffect(() => {
let element = document.getElementById(id);
if (!element) {
element = createElement(id);
appendRootElement(element);
}
setRootElement(element);
return () => {
if (element) {
element.remove();
}
setRootElement(undefined);
};
}, [id]);
return rootElement;
};
export default usePortalRootElement;

View File

@@ -34,7 +34,6 @@
</noscript>
<div id="root"></div>
<div id="modalRoot"></div>
<div id="toastRoot"></div>
<!--
This HTML file is a template.