DEV Community

loading...
Cover image for Adding notifications with React-Toastify

Adding notifications with React-Toastify

proiacm profile image CiaraMaria ・1 min read

Yesterday I came across this npm while searching for different ways to display alerts in my React app. It's react-toastify! In their own words:
"🎉 React-Toastify allows you to add notifications to your app with ease. No more nonsense!"

That's no joke. Installation and integration was a breeze and the notifications are fun and customizable.

Getting started

For this walkthrough, I started up a react application with:

create-react-app toastify-example

and installed Toastify by running:

npm install --save react-toastify

Toastify at work

Make sure you add the imports at the top of your file:

 import { ToastContainer, toast } from 'react-toastify';
 import 'react-toastify/dist/ReactToastify.css';
Enter fullscreen mode Exit fullscreen mode

Then simply add the following:

 const notify = () => toast("Here is my notification!");

    return (
      <div className="App">
       <header className="App-header">
        <button onClick={notify}>Click Me!</button>
        <ToastContainer 
        position="top-center"
        autoClose={5000}
        hideProgressBar={false}
        newestOnTop={false}
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        />
      </header>
    </div>
  );
 }
Enter fullscreen mode Exit fullscreen mode

The additional props are customizable and examples are available on the demo page.

The product:

Example usage in form submission

I personally implemented this as confirmation for a contact form submission. Simply add toast into the submitHandler:

submitHandler = (event) => {
    event.preventDefault()
    event.currentTarget.reset();
    toast.success("Thank you for contacting us!");
  }
Enter fullscreen mode Exit fullscreen mode

Note: toast.success in the example above is one of the presets for styling.

Conclusion

React-Toastify is a neat and simple way to add notifications to your site.

P.S. It's also mobile-friendly with swipe to close. 👌

Discussion (3)

pic
Editor guide
Collapse
itsasine profile image
ItsASine (Kayla)

My team just added toastify and it weirds me out every time it knows I switched to doing other things so it pauses until I come back haha

Collapse
fkhadra profile image
Fadi Khadra

Yes this is the pauseOnFocusLoss feature. It can be disabled if needed 😁

Collapse
fkhadra profile image
Fadi Khadra • Edited

Hey there. I'm the author of react-toastify. I'm really glad you liked it !