You can toast with react components.
Toast API
const CustomToastWithLink = () => (
<div>
<Link to="/toasttest">This is a link</Link>
</div>
);
Toast by toast.info(CustomToastWithLink);
React-Router v5
Example Usage
import React from "react";
import { BrowserRouter as Router, Link, Switch, Route } from "react-router-dom";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const CustomToastWithLink = () => (
<div>
<Link to="/toasttest">This is a link</Link>
</div>
);
const Home = () => {
const letsToast = () => {
toast.info(CustomToastWithLink);
};
return (
<div>
<h3>Home</h3>
<button type="button" onClick={letsToast}>
Toast!
</button>
</div>
);
};
const ToastTest = () => (
<div>
<h3>Toast Test</h3>
Toast Test Satisfactory
</div>
);
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Router>
<Switch>
<Route path="/toasttest" component={ToastTest} />
<Route component={Home} />
</Switch>
<ToastContainer />
</Router>
</div>
);
}
React-Router v6
If you are using the RR6 regular routers then the pattern is exactly the same as RRv5, replacing Switch
with the Routes
component and using the correct Route
props. If you are using the Data APIs though, e.g. createBrowserRouter
then you'll need to create a layout route to provide the ToastContainer
so it's rendered within a routing context.
Example:
import {
createBrowserRouter,
RouterProvider,
Link,
Outlet
} from "react-router-dom";
const ToastProvider = () => (
<>
<Outlet />
<ToastContainer />
</>
);
const router = createBrowserRouter([
{
element: <ToastProvider />,
children: [
{
path: "toasttest",
element: <ToastTest />
},
{
path: "*",
element: <Home />
}
]
}
]);
<RouterProvider router={router} />