Search code examples
reactjsreact-toastify

Toastify Reactjs adding a link


How do I add a link like 'Click here to view' in reactjs toastify and link it to some other url? Currently I can only add static text to it. I used:

toast.info('some text')

And I want to display another line saying click here to view with a href property


Solution

  • 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>
      );
    }
    

    Edit Custom Toastify Toast with React Component

    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} />
    

    Edit Custom Toastify Toast with React Component (forked)