React Modal handling (WIP)

Date: 2022-07-20
import { Button, Modal } from "antd";
import { useRef, useState } from "react";
import ReactDOM from "react-dom";

interface ISelectorProps {
    onSelected: (item?: string) => any;
}

export function MyStringSelector(props: ISelectorProps): JSX.Element {
    const { onSelected } = props;
    return <>
        <Button onClick={() => onSelected("A")}>A</Button>
        <Button onClick={() => onSelected("B")}>B</Button>
        <Button onClick={() => onSelected("C")}>C</Button>
    </>;
}

interface IProps {
    title: string | JSX.Element;
    selector: JSX.Element;
    onSelect: () => any;
    onCancel: () => any;
}

export function SelectorModal(props: IProps): JSX.Element {
    const { title, selector, onSelect, onCancel } = props;
    const [isModalVisible, setIsModalVisible] = useState(true);
    const myRef = useRef(null);
    function handleOk() {
        onSelect();
        unmount();
    }
    function handleCancel() {
        onCancel();
        unmount();
    }
    function unmount() {
        setIsModalVisible(false);
        if (!myRef.current) return;
        setTimeout(() => ReactDOM.unmountComponentAtNode(myRef.current!), 500);
    }
    return <div ref={myRef}>
        <Modal title={title} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>{selector}</Modal>
    </div>
}

function selectAValue() {
    return new Promise<string | undefined>((resolve) => {
        let selectedValue: string | undefined = undefined;
        ReactDOM.createPortal(<SelectorModal title="Selecteer een waarde" onSelect={() => resolve(selectedValue)} onCancel={() => resolve(undefined)} selector={<MyStringSelector onSelected={(x) => selectedValue = x} />} />, document.body);
    });
}


async function Test() {
    const result = await selectAValue();
    // if (result.selectedLine) {
    //     // set it!
    // }
}
64040cookie-checkReact Modal handling (WIP)