Implement Toast Notification In React Using Primereact

Hello Developers, In this blog, we are going to learn how we can implement toast notifications in our app using prime-react

First of all, create a new app using the following command:

npx create-react-app

After that install following packages in your app using following methods

npm i primereact primeicons

After installation, import necessary files in your app.js

import "primereact/resources/themes/lara-light-indigo/theme.css";
import "primereact/resources/primereact.min.css";
import "primeicons/primeicons.css";

Now you’re good to go, import toast component in your file

import { Toast } from 'primereact/toast';

Now create a ref object which we will use to show toast

const toast = useRef(null)

Now call Toast component to render it and give ref object to it

<div
    style={{
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center'
    }}>
    <Toast ref={toast} />
    <Button onClick={showToast}>Show</Button>
</div>
toast.current.show({ severity: 'success', summary: 'Success Message', detail: 'Order submitted' });

Basically, severity is a type of toast message.  (error, success, info, etc…)

Summary is a summary (title) of the toast message

Detail is main detail of toast message which you want to show

Demo:

You can also set position of toast message

<Toast ref={toast} position='top-left' />

You can also set timeout for toast message which is 3 seconds (3000 ms) by default

toast.current.show({ life: 1000, severity: 'success', summary: 'Success Message', detail: 'Order submitted' });

Demo:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories