DEV Community

Cover image for Setting Up Toast Custom Notifications in React with Specific Types and Context API
Akash Yadav
Akash Yadav

Posted on

1

Setting Up Toast Custom Notifications in React with Specific Types and Context API

Context Setup

src/context/ToastContext.js

import { createContext, useCallback, useContext, useEffect, useState } from "react";

const CreateAlertBox = createContext();

export const useCreateAlert = () => useContext(CreateAlertBox);

const AlertType = ['error', 'success', 'info', 'warning'];

export const CreateAlertBoxProvider = ({ children }) => {
    const [alert, setAlert] = useState([]);

    const createAlert = useCallback((message, type = 'warning') => {
        if (!AlertType.includes(type)) return;

        setAlert((prevAlert) => [
            ...prevAlert,
            { id: Date.now(), message, type }
        ])
    }, [])

    const removeAlert = useCallback((id) => {
        setAlert((prevAlert) => prevAlert.filter((alert) => alert.id !== id));
    }, [])
    return (
        <CreateAlertBox.Provider value={{ createAlert, removeAlert }}>
            {children}
            <div className="toast-container">
                {
                    alert.map((alert) => (
                        <div key={alert.id} className={`toast toast-${alert.type}`}>
                            {alert.message}
                            <button onClick={() => removeAlert(alert.id)}>X</button>
                        </div>
                    ))
                }
            </div>
        </CreateAlertBox.Provider>
    )
}
Enter fullscreen mode Exit fullscreen mode

CSS for Toast Notifications

/* src/styles/toast.css */

.toast-container {
    position: fixed;
    top: 1rem;
    right: 1rem;
    z-index: 9999;
}

.toast {
    background-color: #333;
    color: #fff;
    padding: 1rem;
    margin-bottom: 1rem;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.toast-info {
    background-color: #007bff;
}

.toast-success {
    background-color: #28a745;
}

.toast-warning {
    background-color: #ffc107;
}

.toast-error {
    background-color: #dc3545;
}

.toast button {
    background: none;
    border: none;
    color: #fff;
    cursor: pointer;
    margin-left: 1rem;
}

Enter fullscreen mode Exit fullscreen mode

Providing the Toast Context

// src/main.js

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { RouterProvider } from 'react-router-dom'
import { router } from './router.jsx'
import { CreateAlertBoxProvider } from './context/toastcontext.jsx'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <CreateAlertBoxProvider>
        <RouterProvider router={router}>
          <App />
        </RouterProvider>
    </CreateAlertBoxProvider>
  </React.StrictMode>,
)

Enter fullscreen mode Exit fullscreen mode

Using the Toast Context in Components

import React, { useContext, useEffect } from 'react'
import { UserContext } from '../context/usercontext'
import { useCreateAlert } from '../context/toastcontext'

const Profile = () => {
    const { user } = useContext(UserContext)

    const { createAlert } = useCreateAlert();

    const showToast = () => {
        try {
            createAlert("Deal created successfully", 'success')

        } catch (error) {
            createAlert('This is an info toast!', 'error');
        }
    };


    return (
        <div className="App">
            <p>Hello Profile</p>
            <button onClick={showToast}>Show Toast</button>
        </div>
    )
}

export default Profile
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

Identify what makes your TTFB high so you can fix it

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay