Welcome folks today in this blog post we will be using the react-hot-toast
library to show colorful toast
notification messages in Javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to create the react.js project and install the below library
using the below command as shown below
npx create-react-app sampleapp
cd sampleapp
npm i react-hot-toast
npm i react-icons
And after that you will see the below directory structure of the react.js
project as shown below
And now we need to write code inside the App.js
file and copy paste the following code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
import "./styles.css"; import { AiFillAndroid } from "react-icons/ai"; import toast, { Toaster } from "react-hot-toast"; const dismissToast = () => toast.remove(); const successToast = () => toast.success("Here is your toast."); const customToast = () => toast((t) => ( <span> I am a custom toast{" "} <button onClick={() => toast.dismiss(t.id)}>Dismiss</button> </span> )); const errorToast = () => toast.error("error toas", { duration: 7000, iconTheme: { primary: "#000", secondary: "blue" }, role: "status", ariaLive: "polite", style: { background: "red", color: "whitesmoke" }, icon: <AiFillAndroid /> }); export default function App() { return ( <div> <button onClick={successToast}>Success toast</button> <button onClick={errorToast}>Error toast</button> <button onClick={dismissToast}>Remove all toasts</button> <button onClick={customToast}>custom toast</button> <Toaster position="bottom-left" toastOptions={{ duration: 3000, iconTheme: { primary: "red", secondary: "white" }, role: "status", ariaLive: "polite", style: { background: "green", color: "whitesmoke" } }} /> </div> ); } |
As you can see we are importing the react-icons
and react-hot-toast
libraries at the top and then we are using the different types of notifications
such as the error
and success
and then we are also showing the custom toast
notification as well. And also we have attached different background and secondary
colors as well using the options. And also we are attaching different icons using the react-icons
package and then duration
property which tells how much time the notification
should stay on the page.