Skip to content

Instantly share code, notes, and snippets.

@ercnshngit
Created May 16, 2024 07:20
Show Gist options
  • Save ercnshngit/c5b23048b80ca63b225515324385f3cc to your computer and use it in GitHub Desktop.
Save ercnshngit/c5b23048b80ca63b225515324385f3cc to your computer and use it in GitHub Desktop.
Simple react popup manager
import React from 'react'
export default function layout({children}) {
return (
<html>
<body>
<PopupManagerContextProvider>
{children}
</PopupManagerContextProvider>
</body>
</html>
)
}
import React from 'react'
export default function Popup({children, name}) {
const {openedPopup} = usePopupManager()
if(openedPopup !== name) return null
return createPortal(
<div>
{children}
</div>,
document.body
)
}
import React from 'react'
export default function OpenPopupButton() {
const {setOpenedPopup} = usePopupManager()
return (
<button onClick={() => setOpenedPopup('popup1')}>
Open Popup
</button>
)
}
import { createContext, ReactNode, useContext, useState } from "react";
//ekranda 1 tane popup gozukecekse tek yapmak daha mantikli sanki
interface PopupManagerProps {
openedPopup: string;
setOpenedPopup: (popup: string) => void;
}
export const PopupManagerContext = createContext<PopupManagerProps>({
openedPopup: "",
setOpenedPopup: () => {},
});
export const PopupManagerContextProvider = ({
children,
}: {
children: ReactNode;
}) => {
const [openedPopup, setOpenedPopup] = useState<string>("");
return (
<PopupManagerContext.Provider
value={{
openedPopup,
setOpenedPopup,
}}
>
{children}
</PopupManagerContext.Provider>
);
};
export const usePopupManager = () => useContext(PopupManagerContext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment