Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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?

like image 469
sam23 Avatar asked Jul 25 '17 04:07

sam23


3 Answers

you should install package https://www.npmjs.com/package/react-toastify and then add import and add

<ToastContainer />

in your header or some component like sidebar which is being used at every page. You can now show toast messages on any page by just

toast.error("this is toast error"); 
like image 168
Zaman Afzal Avatar answered Oct 12 '22 11:10

Zaman Afzal


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 !

like image 5
Eugène Beliaev Avatar answered Oct 12 '22 10:10

Eugène Beliaev


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');
like image 1
André Rodrigues Avatar answered Oct 12 '22 12:10

André Rodrigues