🐛(react) fix default opened modal
Modal with isOpen=true on first render were causing a crash. With this approach we make sure the portal node is already rendered. Fixes #259
This commit is contained in:
@@ -7,6 +7,22 @@ import { useModals } from ":/components/Modal/ModalProvider";
|
|||||||
import { VariantType } from ":/utils/VariantUtils";
|
import { VariantType } from ":/utils/VariantUtils";
|
||||||
|
|
||||||
describe("<Modal/>", () => {
|
describe("<Modal/>", () => {
|
||||||
|
it("shows a modal opened by default", async () => {
|
||||||
|
const Wrapper = () => {
|
||||||
|
const modal = useModal({ isOpenDefault: true });
|
||||||
|
return (
|
||||||
|
<CunninghamProvider>
|
||||||
|
<button onClick={modal.open}>Open Modal</button>
|
||||||
|
<Modal size={ModalSize.SMALL} {...modal}>
|
||||||
|
<div>Modal Content</div>
|
||||||
|
</Modal>
|
||||||
|
</CunninghamProvider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
render(<Wrapper />);
|
||||||
|
expect(await screen.findByText("Modal Content")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
it("shows a modal when clicking on the button", async () => {
|
it("shows a modal when clicking on the button", async () => {
|
||||||
const Wrapper = () => {
|
const Wrapper = () => {
|
||||||
const modal = useModal();
|
const modal = useModal();
|
||||||
|
|||||||
@@ -52,6 +52,23 @@ export interface ModalProps
|
|||||||
}> {}
|
}> {}
|
||||||
|
|
||||||
export const Modal = (props: ModalProps) => {
|
export const Modal = (props: ModalProps) => {
|
||||||
|
/**
|
||||||
|
* This is a workaround to prevent the modal from rendering on the first render because if the modal is open on the
|
||||||
|
* first render, it will not be able to resolve document.getElementById("c__modals-portal") which is not rendered yet.
|
||||||
|
*/
|
||||||
|
const [firstRender, setFirstRender] = React.useState(true);
|
||||||
|
useEffect(() => {
|
||||||
|
setFirstRender(false);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (firstRender) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <ModalInner {...props} />;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ModalInner = (props: ModalProps) => {
|
||||||
const ref = React.useRef<HTMLDialogElement>(null);
|
const ref = React.useRef<HTMLDialogElement>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|||||||
Reference in New Issue
Block a user