How to show toast error message in react


In react, toast is a great concept to notify your clients when they click on a button so that they are sure that the action that has been requested is fully completed or failed
In this article we are going to explain how to show toast message error
Install react toastify
We need first to install react toastify in the root directory of our project
npm i react-toastify
yarn add react-toastify
then we need to import react toastify css and container in our js file to use it
the import look like :
import { toast ,ToastContainer} from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
Show toast error message
To show toast error message, set type to error when calling toast like this toast("Error notification", { type: "error" }) so that the toast will be appeared in red underline and exclamation mark
In your react app, the final code will look like :
Edit App.js
import { toast ,ToastContainer} from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
export default function Test() {
const onClick = () => toast("Error notification", { type: "error" });
return (
<>
<button onClick={onClick}> Click Me</button>
<ToastContainer />
</>
);
}
Toast success message
In the same way, when you set toast options type to success, the toast will be shown up in green to let the user understand that everything is going accroding to plan
The code will look like :
import { toast ,ToastContainer} from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';
export default function Test() {
const onClick = () => toast("Success notification", { type: "success" });
return (
<>
<button onClick={onClick}> Click Me</button>
<ToastContainer />
</>
);
}
Test configuration
Run your server and hit localhost:3000 or whatever port you are using for dev server, and click on the button on the top left of the screen
The toast will look like this:
It is also possible to use values for type like info, warning and default . Feel free to set the type to these values and see the results by yourself
Conclusion
We have seen how to show toast error, success, info and warning message in react