I would create a toast context that would allow showing toasts
toast-context.js
import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.css";
import { Toast } from "primereact/toast";
import { createContext, useContext, useRef } from "react";
// create context
const ToastContext = createContext(undefined);
// wrap context provider to add functionality
export const ToastContextProvider = ({ children }) => {
const toastRef = useRef(null);
const showToast = (options) => {
if (!toastRef.current) return;
toastRef.current.show(options);
};
return (
<ToastContext.Provider value={{ showToast }}>
<Toast ref={toastRef} />
<div>{children}</div>
</ToastContext.Provider>
);
};
export const useToastContext = () => {
const context = useContext(ToastContext);
if (!context) {
throw new Error(
"useToastContext have to be used within ToastContextProvider"
);
}
return context;
};
index.js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { ToastContextProvider } from "./toast-context";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<ToastContextProvider>
<App />
</ToastContextProvider>
</StrictMode>
);
App.js
import { useToastContext } from "./toast-context";
export default function App() {
// use context to get the showToast function
const { showToast } = useToastContext();
const handleClick = () => {
http(showToast);
};
return (
<div className="App">
<button onClick={handleClick}>show toast</button>
</div>
);
}
// pass showToast callback to your http function
function http(showToast) {
showToast({
severity: "success",
summary: "Success Message",
detail: "Order submitted"
});
}
Codesanbox example: https://codesandbox.io/s/beautiful-cray-rzrfne?file=/src/App.js