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?
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");
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With