How to use the useToast hook for displaying notifications in Next.js



Image not found!!


In Next.js, you can use the react-toast-notifications library to display notifications. The useToast hook is a part of this library and makes it easy to show notifications in your Next.js application.

Here are the steps to use the useToast hook:

  1. Install the react-toast-notifications library:

    Run the following command in your Next.js project to install the library:

    bash
    npm install react-toast-notifications

    Or if you are using Yarn:

    bash
    yarn add react-toast-notifications
  2. Import and use the useToast hook in your component:

    In your component file, import the useToasts hook from the library:

    jsx
    import { useToasts } from 'react-toast-notifications';

    Then, use the useToasts hook to get the addToast function, which you can use to display notifications:

    jsx
    import React from 'react'; import { useToasts } from 'react-toast-notifications'; const MyComponent = () => { const { addToast } = useToasts(); const showToast = () => { addToast('Notification message', { appearance: 'success', autoDismiss: true }); }; return ( <div> <button onClick={showToast}>Show Notification</button> </div> ); }; export default MyComponent;

    In the example above, when the button is clicked, a success notification with the message "Notification message" will be displayed. You can customize the appearance, autoDismiss duration, and other options based on your requirements.

  3. Customize the notification appearance:

    The appearance prop in the addToast function allows you to specify the appearance of the notification. Some common values include 'success', 'error', 'warning', and 'info'.

    jsx
    addToast('Error message', { appearance: 'error', autoDismiss: true });

    You can customize the appearance and other options according to your application's needs.

That's it! You should now be able to use the useToast hook from the react-toast-notifications library to display notifications in your Next.js application.