How To create a Global Component like Toast in React And Refer it in any other component?

Viewed 14745

I am trying to create a App using React. I want to add a toast component globally to the app so that it can be referred by other component for displaying custom messages.

I want to add the toast in the following hierarchy:

ReactDOM.render(
        <BrowserRouter>
            <section>
                  <App />
                  <Toast />
            </section>
        </BrowserRouter>

And refer the Toast Component inside the App. How can I implement it?

5 Answers

First you need to import the ToastContainer and the CSS file :

import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

and then inside the App.js add the ToastContainer on top :

<React.Fragment>
        <ToastContainer />
        <NavBar ... />
        ....
</React.Fragment>

And then you can use the toast popups in any of your components, classes and functions by importing Toast:

import { toast } from "react-toastify";

and then using it with toast() or toast.error() or toast.info() etc methods

toast("Wrong email or Password");
...
toast.error("Some kind of Error");

Hope it helps !

I've tried that approach (including ToastContainer component), but the toast.something didn't fire the event through the Toast component. The solution I've implemented was creating a function that mimics a component behavior, and instead of passing conditionals through props, pass arguments. Here's an example:

import React from "react";
import { toast } from "react-toastify";

const Toast = (message, type) => {
  switch (type) {
    case "success":
      return toast.success(
        <div>
          <p>{message}</p>
        </div>
      );
    case "error":
      return toast.error(
        <div>
          <p>{message}</p>
        </div>
      );
    case "warning":
      return toast.warning(
        <div>
          <p>{message}</p>
        </div>
      );
    default:
      return toast.warning(
        <div>
          <p>Toast not defined...</p>
        </div>
      );
  }
};
export default Toast;

Somewhere in the component:

Toast('Action successfully executed!', 'success');
Related