Toast Stack

MediumReact Components20 min5 tests

Build a toast notification stack: an "Add toast" button appends dismissible toasts, each shows as an alert, and a live status reports the current toast count.

Create a App component that manages a stack of toast notifications.

There is an "Add toast" button. Each time it is clicked, a new toast is appended to the stack. A toast is rendered with role="alert" and the visible text Toast {n}, where n is the toast's sequential number (the first toast added is Toast 1, the second is Toast 2, and so on — numbers always increase and are never reused, even after earlier toasts are dismissed).

Every toast has its own "Dismiss" button. Clicking a toast's Dismiss button removes only that toast from the stack; the other toasts remain untouched.

A live region with role="status" always reports the current count as {n} toasts (e.g. 0 toasts, 1 toasts, 3 toasts). The wording uses the literal word "toasts" regardless of the number.

Initially the stack is empty: the status reads 0 toasts and no alerts are present.

Requirements

  • Render an "Add toast" button that appends a new toast each time it is clicked.
  • Each toast has role="alert" and visible text "Toast {n}" where n is a sequential, never-reused number starting at 1.
  • Each toast renders its own "Dismiss" button that removes only that toast.
  • Render a role="status" live region showing the text "{n} toasts" reflecting the current number of toasts.
  • Start with no toasts: the status shows "0 toasts" and there are no alerts.
Hints (3)
  1. Track toasts in state as an array of objects, each with a stable unique id and its display number. Use a separate ever-increasing counter (e.g. a ref or a piece of state) so numbers are never reused after a dismiss.
  2. Removing a toast is a filter by id; the status text is derived from the array length on every render, so it stays in sync automatically.
  3. Give icon/short-label buttons accessible names. Here the buttons already have visible text ("Add toast", "Dismiss"), so getByRole('button', { name }) can find them.

Topics

  • React
  • React Components

Asked at

BookMyShow · Uber · Meesho · MakeMyTrip · Microsoft · Zerodha

Join Us
blur