Home / Companies / LogRocket / Blog / Post Details
Content Deep Dive

Implementing animated toasts in React

Blog post from LogRocket

Post Details
Company
Date Published
Author
Aditya Agarwal
Word Count
2,024
Language
-
Hacker News Points
-
Summary

A toast is a UI element designed to convey messages to users unobtrusively, typically appearing at the bottom of the screen and disappearing after a brief duration. The article outlines the process of creating animated toasts in a React application using Framer Motion for animations and React portals for DOM manipulation, with Zustand managing the toast state. The implementation involves creating a `Toasts.js` file comprising a Zustand store, a Toast component, and a `useToastControls` custom hook. The Zustand store maintains a list of active toast IDs and provides methods to show, close, and close all toasts. The Toast component uses the Zustand store to determine which toasts are displayed and animates them using Framer Motion, while React portals ensure they appear in a designated DOM node. The `useToastControls` hook exposes methods for managing toasts while keeping the internal state protected. The article also suggests enhancements such as setting display limits and default durations for toasts, leaving these advanced features as an exercise for the reader.