Developing Custom Toaster Functionality for React Application from Scratch

Solution Architect

12 Jul 20239 min read

Developing Custom Toaster Functionality for React Application from Scratch

In this article you’ll learn how to add your own custom toast messages to a react application without using any third-party toaster libraries.

Toast messages are a crucial part of every web application. Toast messages are used to inform the user of the status or output of different tasks. Without these, it becomes extremely difficult for a user to effectively utilize the application. Hence, while developing an application, having the ability to create distinctive and relevant status messages is definitely a bonus.

There are numerous toaster libraries for react as of right now, and re-using these in application to save time is usually the best option. However, there may be times when special use cases or functionalities must be introduced that are outside the purview of these libraries. In this article, I’ll provide a basic walkthrough of how you can build your own toast functionality into a react application. I am not trying to build a complex functionality here, it’s just to give you a general idea of how to tackle these problems, and might come in handy for future challenges as well.

Ideation

Let’s start by making a note of our goals and what features our application should have to fulfil them.

Goals

  1. A shared state to store the messages.

  1. Each message should have a context i.e., success, warning, error, info etc.

  1. A function that can be called from any inner component to add or remove toast messages.

  1. A user interface to show the messages on screen.

  1. The messages should disappear after a specified timeout.

  1. There should be a limit to how many messages can appear at once on the screen.

  1. Newer messages should come on top of the older ones.

Features

1.We can either use React Context or Redux or any state management libraries to achieve the shared state. I’ll be using zustand which is a state management library for react with a much less boilerplate code compared to Redux (because its my favourite).

2.The goals [2] & [4] can be accomplished by creating a react component with a prop value for the context (success/info/error etc.).

3.We can make use of mutations/actions on your store to update messages on the store. However, this might cause problems when you need to add more features or modify a particular feature. So, we’ll create a custom hook function to wrap around the state mutation logic, giving a specific and easy-to-use utility as well as giving us the ability to modify our toaster functionality at a later stage without breaking the application..

4.The custom hook fits in pretty well for the timeout feature. We can just use the setTimeout method and call the remove action for the message. (Note: This would mean we have to give a unique id to each message we add to the store).

5.We’ll use a fixed-size array to tackle the goals [5] & [6]. We can add new messages to start of array and take only the first ’N’ elements (’N’ being the message limit). If we write it down in code, it’ll look somewhat like this:

messages = [newMessage, ...messages].slice(0, N)

Designing

The next step is to design our toast messages. In an actual application, the design might be done by a different person or a different dedicated team. This is not too important for this article, so I won’t go into much details.

I’ve used Figma to design the toast message and a simple screen for our application to showcase the functionality. I used a few plugins to speed up the design process which I’ll be mentioning below.

toaster_1.png

The toast message component for each context

toaster_2.png

Plugins Used

  • Tailwind Color Palettes — Since I’m going to use tailwindcss for development.
  • RemixIcon — For the icons in the design.
  • Logoipsum — For the placeholder logo used in header.

For anyone interested, you can access the Figma design from here👈

Development

Now, its time to start coding. I’ll be using pnpm as my package manager, but if npm or yarn work better for you, by all means, use those instead. As I’ve already stated, I’ll be focusing more on delivering the concept rather than the entire code base. So I won’t go into depth about every line of code here.

Scaffolding the application

I’ll use Vite to scaffold a react application with the TypeScript template. If you are not familiar with TypeScript, feel free to use JavaScript instead. It won’t really matter since the concept and the process are same for both.

pnpm create vite custom-toaster --template react-ts

I’ll also install the required dependencies. In this case:

  • TailwindCSS for styling (Follow this link for steps to install and setup tailwind).
  • React Router Dom for routing.

pnpm add react-router-dom@6

  • Zustand for state management

pnpm add zustand

  • React Icons

pnpm add react-icons

I’ve used the Sora font in design. I’ll include it in the application and configure tailwind to use it as the default font family.

_assets_blogs_arjunp_blog_screen_1.webp

_assets_blogs_arjunp_blog_screen_2.webp

We also need to setup the router before moving on to the next step.

_assets_blogs_arjunp_blog_screen_3.webp

Creating the Layout and Pages

Since our application is fairly simple, it will have a single layout that houses the header, sidebar and the content of each page. In the coming steps, we will use the layout to house the toast messages as well.

We’ll create two pages — A home page and an articles page, both with the same design and functionality i.e., to send and clear toast messages. The purpose of creating two pages is only to demonstrate the fact that the toast trigger can be used in any page.

_assets_blogs_arjunp_blog_home.webp

_assets_blogs_arjunp_blog_screen_5.webp

Our source folder will have the following files after finishing this step:

Components

  • Button.tsx— for the ‘Show Toast’ and ‘Clear All’ buttons.

_assets_blogs_arjunp_blog_screen_6.webp

  • HeroTitle.tsx — for the large ‘Home’ and ‘Article’ texts in each page.

_assets_blogs_arjunp_blog_screen_7.webp

Layouts

  • MainLayout.tsx

_assets_blogs_arjunp_blog_screen_8.webp

Partials

  • Header.tsx — For the header part of the layout.

_assets_blogs_arjunp_blog_screen_9.webp

  • Sidebar.tsx — The sidebar with the page links

_assets_blogs_arjunp_blog_screen_10.webp

Pages

  • HomePage.tsx

_assets_blogs_arjunp_blog_screen_11.webp

_assets_blogs_arjunp_blog_screen_12.webp

We’ll also add routes to our pages:

_assets_blogs_arjunp_blog_screen_13.webp

Creating the Toaster Component

Now, since we’ve setup our basic application, it’s time to get to the actual problem in hand —The Toaster.

To begin with, we’ll be creating the necessary components and adding it to the layout. In the next steps, we’ll setup the store and write the core functionalities.

First, we’ll create the component for a single toast message. Let’s take a look at what the capabilities of our component should be:

1.It should have a prop for the content of the message.

2.It should have a prop for the context of the message — the icon and color changes based on this property.

3.Should be able to pass a callback function that is triggered whenever the close button is pressed (This will also be passed in as a prop to the component).

_assets_blogs_arjunp_blog_screen_14.webp

Once we have the 'ToastMessage' component, we need a container component to place these messages. In the later stages, some of our toast message functionalities will also be added to this container component.

We will create a new component inside the partials. _assets_blogs_arjunp_blog_screen_15.webp

In the upcoming steps, the data from our store will replace the hardcoded array of messages that we currently use to render the messages.

Next, we’ll include this component inside the 'MainLayout'.

_assets_blogs_arjunp_blog_screen_16.webp

Our application home page would now look somewhat like this:

_assets_blogs_arjunp_blog_screen_17.webp

Setting up the Store

Settings up a store in zustand is really simple and straightforward. Zustand exposes a create function that returns a custom hook which we can use to access our store instance. Let’s create our toaster store.

We’ll create a toaster.ts file inside stores directory to hold our store logic.

In our store, we’ll have

  • An array state to hold the messages.
  • An action to add message.
  • An action to remove a particular message.
  • An action to clear all messages.

_assets_blogs_arjunp_blog_screen_18.webp

We’ll also create a custom hook to make interacting with the store easier as well as to include the timeout functionality.

_assets_blogs_arjunp_blog_screen_19.webp

Here, we created a separate method for each message context. This can be modified based on needs to include more complex features.

In the next steps, we’ll integrate the store to the components to complete the functionality.

Retrieving messages from Store

In this step, we’ll replace our hardcoded set of messages in ToastContainer with the messages in our store.

_assets_blogs_arjunp_blog_screen_20.webp

Triggering the Toast Message

All that is left to do is to use our useToaster hook inside the page and add some messages to our store which will be updated in the ToastContainer to display the messages on screen.

_assets_blogs_arjunp_blog_screen_21.webp

_assets_blogs_arjunp_blog_screen_22.webp

Now we can trigger toast messages from any page inside the MainLayout.

Next, we’ll add the close button functionality to remove the message from screen. We will use the store action removeMessage to achieve this.

_assets_blogs_arjunp_blog_screen_23.webp

Yay!!! that’s it. We’ve successfully added a toast functionality to our react application 👏.

What we’ve done so far

  • Scaffolded a react application to add toaster functionality.
  • Designed and developed the component for the toast message and the container.
  • Created a store to hold the messages and added actions to add, remove and clear messages.
  • Created a custom useToaster hook to make interaction with our store much easier.
  • Modified the ToastContainer component to display messages from the store and to remove messages when close button is clicked.
  • Used the useToaster hook to trigger toast messages from different pages in our application.

Now, you can start experimenting more on top of this to make it much more interactive. As a bonus, I’m also going to show how to add animations to these messages when they are displayed.

Bonus — Adding Animations

Right now, our toast messages look slightly boring. Let’s add some animations to make it more appealing. We’ll use a library called Framer Motion to add some really cool enter and exit animations to our toast messages.

Install Framer Motion

pnpm add framer-motion

Add 'AnimatePresence' to the 'Toast Container'

According to Framer Motion docs, the AnimatePresence component allows components to animate out when they’re removed from the React tree since React lacks the lifecycle method that:

  • Notifies components when they’re going to be unmounted and
  • Allows them to defer that unmounting until after an operation is complete (for instance an animation).

In short, it is necessary to add this component in-order to add exit animation.

_assets_blogs_arjunp_blog_screen_24.webp

Adding animation to 'ToastMessage' component

Now we’ll add animations to the ToastMessage component. To do this we need to replace our root div element with the framer motion’s motion.div element. This will let us add some animation properties to our component:

  • initial — The initial properties for the component.
  • animate — The properties to change (animate) once the component is mounted.
  • exit — The properties to change (animate) before the component is unmounted.

_assets_blogs_arjunp_blog_screen_25.webp

Now, when you click the “Show Toast” button, you’ll see that the toast message appears with a neat fade-in animation and exits with a fade-out animation. But if we add more toast messages, the old messages are pushed down instantly which makes it look a bit clumsy. This is because we are only animating the messages and not the layout itself. Don’t worry, framer motion has something exactly for this kind of situation — Layout.

Layout helps us animate layout changes that happens due to re-renders. Here, it helps us to animate the parent div element that holds all the toast messages whenever new messages are added to it. To achieve this, we need to convert it to a motion.div and add the layout property. We’ll also add layout property to our 'ToastMessage' component as well to avoid distortion during the animation.

_assets_blogs_arjunp_blog_screen_26.webp

_assets_blogs_arjunp_blog_screen_27.webp

Congratulations🎊!! Our React application now features a really cool toaster functionality.

Conclusion

The purpose of this article was to give a fair idea on how to add custom functionality to a React application. I chose the problem of adding a toaster since it doesn’t involve too much designing and it’s fairly easier to understand and implement. You can follow a similar approach to most of the design problems while creating a frontend application irrespective of the framework (React, Angular, Vue etc.).

You can get the final source code from the Github repo: https://github.com/a2-coder/tutorial-custom-toaster

If this article was helpful to you (I really hope so), give a 👏to keep me motivated to come up with more and more contents like this.

Build with us. Deploy with us. Win with us

We don't deliver projects and walk away. We build with you, inside your mission.

Book a strategic consultation